Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

trying to do some operations on all the files in the directory that end in .c (C files). The code is:

#!/bin/sh
clear
for file in *
do
    if [ $file="*.c" ]
    then
        echo $file
    fi
done
exit 0

doesn't work. it just lists all the files and directories.

share|improve this question
    
take a look here stackoverflow.com/questions/407184/… – LilloX 19 hours ago
    
you've a test problem not if ! see man test ; in terminal run "man test" – younes 12 hours ago

3 Answers 3

The condition on if is malformed, you're just checking that the string $file=*.c isn't empty. Try instead:

#!/bin/sh
clear
for file in *
do
    if [ "$file" = "*.c" ]
    then
        echo "$file"
    fi
done
exit 0

On the other hand, the comoding char '*' in this case is not functional, but it's interpreted to a string.

Try:

#!/bin/sh
clear
for file in *.c
do
    echo "$file"
done
exit 0
share|improve this answer
    
It most not be $file in the for statement. – Bananguin 18 hours ago
1  
Only a single = for POSIX compliance. – phk 16 hours ago
    
... and put quotes around your variable substitutions i.e. "$file" – Murray Jensen 14 hours ago
    
The if condition still only be true for a file named *.c. It does not check if $file ends with .c, does it. – Bananguin 8 hours ago

Your test statement does not check if the file's suffix is .c. It checks (in most cases) if $file is equal to *.c, see test(1).

However, if you replaced your for statement to read

for file in *.c

the for statement would only be passed the files ending with .c so you don't have to check anymore.

share|improve this answer

Another one liner way would be the usage of find:

find . -name "*.c" | xargs echo

It depends on what you actually want to do with those files so that this helps you.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.