if[ "$x"="*.c" ] then echo $x else echo "not .c"
I want to examine if the input parameter ends with “.c” (“*.c”).
Advertisement
Answer
The conditional in the posted code is always true,
because the "$x"="*.c"
you have inside the [ ... ]
is interpreted by the shell as a single non-empty string value, and non-empty string values are truthy in Bash.
But why is that a “single non-empty string value”? What about the =
sign?
To be treated as the conditional operator of the [ ... ]
builtin, you must put spaces around the =
sign. Otherwise the shell doesn’t recognize it as an operator.
That is, write like this (fixing other syntax errors as well):
if [ "$x" = "*.c" ]; then echo "$x"; else echo "not .c"; fi
This will make the condition not always true, but it still won’t do what you want. To check if the variable ends with .c you need to write it differently, using the [[ ... ]]
builtin:
if [[ "$x" == *.c ]]; then echo "$x"; else echo "not .c"; fi