2

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.

  • take a look here stackoverflow.com/questions/407184/… – LilloX Nov 4 '15 at 8:50
  • you've a test problem not if ! see man test ; in terminal run "man test" – Jonah Nov 4 '15 at 15:42
  • changing to *.c in the for loop did it. Thanks everyone for the help! – susdu Nov 9 '15 at 19:00
6

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
  • It most not be $file in the for statement. – Bananguin Nov 4 '15 at 9:59
  • 1
    Only a single = for POSIX compliance. – phk Nov 4 '15 at 11:24
  • ... and put quotes around your variable substitutions i.e. "$file" – Murray Jensen Nov 4 '15 at 13:37
  • The if condition still only be true for a file named *.c. It does not check if $file ends with .c, does it. – Bananguin Nov 4 '15 at 19:39
4

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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