Why is only hello3 being printed? There must be some kind of syntax problem because the file list definitely includes all the file extensions line by line.
#!/bin/bash
find '/home/myuser/folder/' -name '*.c' -type f | while read F
do
if [[ "$F" == '*.txt.c' ]] # if the file name ends in .txt.c
then
echo hello1
elif [[ "$F" == '*.c' && "$F" != '*.txt.c' && "$F" != '*.xml.c' ]] # if the file name does end in .c but not in txt.c nor .xml.c
then
echo hello2
else # is this else necessary ?
echo hello3
fi
done
if [[ $F == *.txt.c ]] # if the file name ends in .txt.c
then
echo hello1
elif [[ $F == *.c && $F != *.txt.c && $F != *.xml.c ]] # if the file name ...
then
If I was doing the test you are trying to do with:
which is testing for a file literally called .txt.c, if you changed the test to == ".txt.c" then you would be comparing $F with a list of files in the pwd named <anything>.txt.c.
I would do it as:
if [[ -n "`echo ${F} | grep '\.txt\.c$'`" ]]
But then I tend to write Bourne shell with a few Korn shell enhancements when necessary.[COLOR="\#738fbf"]
Inside [[ ]] word splitting and wildcard expansion are not performed. So if you use == "*.txt.c" you are still comparing to a literal asterisk. Therefore you need to drop the "" as well in the case of pattern. "" are used for literal string matches. So you can use for example:
OK, I just realized that my system uses dash (not bash). So it works with bash but in dash it ouputs these errors. Any idea why? I really want to stick with dash syntax and not use programs like grep etc. when not strictly necessary.
This works in bash but not in dash:
#!/bin/dash
find '/home/myuser/folder/' -name '*.c' -type f | while read F
do
if [[ $F == *.css.c ]]
then
echo hello1
elif [[ $F == *.c && $F != *.txt.c && $F != *.xml.c ]]
echo hello2
else
echo hello3
fi
done
Dash is posix compliant without all the additional bells and whistles that bash provides, so the [[ ... ]] is not available. You can use the [ ... ] construct, but not with patterns. So I think you should use a case statement:
find '/home/myuser/folder/' -name '*.c' -type f |
while read F
do
case $F in
*.css.c) echo hello1 ;;
*.txt.c|*.xml.c) echo hello3 ;;
*.c) echo hallo2 ;;
*) echo hello3 ;;
esac
done