This question is a sequel of sorts to my earlier question. The users on this site kindly helped me determine how to write a bash for loop that iterates over string values. For example, suppose that a loop control variable fname iterates over the strings "a.txt" "b.txt" "c.txt". I would like to echo "yes!" when fname has the value "a.txt" or "c.txt", and echo "no!" otherwise. I have tried the following bash shell script:
#!/bin/bash
for fname in "a.txt" "b.txt" "c.txt"
do
echo $fname
if [ "$fname" = "a.txt" ] | [ "$fname" = "c.txt" ]; then
echo "yes!"
else
echo "no!"
fi
done
I obtain the output:
a.txt
no!
b.txt
no!
c.txt
yes!
Why does the if statement apparently yield true when fname has the value "a.txt"? Have I used | incorrectly?
-owithin the same[ ]. – Thor Sep 08 '12 at 20:53||and separate[ ]over-ofor portability simply because[is not guaranteed to support more than 4 arguments. Of course if the target language isbash, no one should be using[anyways becausebash's[[is superior in many ways. – jw013 Sep 09 '12 at 00:46if [[ "$fname" = "a.txt" ]] || [[ "$fname" = "c.txt" ]]rather thanif [ "$fname" = "a.txt" ] || [ "$fname" = "c.txt" ]? – Andrew Sep 09 '12 at 17:14bash, as you are already doing. One advantage of[[is that it doesn't do word splitting (special case) so[[ $unquoted_var = string ]]is safe. – jw013 Sep 10 '12 at 02:06The XSI extensions specifying the -a and -o binary primaries and the '(' and ')' operators have been marked obsolescent.and should not be used. – William Pursell Jan 04 '20 at 16:50[[(IMO, a complete show stopper) is that it does not produce reasonable error messages, but happily returns truthiness with no error message to statements like[[ $a -eq 0 ]]when $a is not an integer value. In other words, if the target language is bash, no one should be using[[at all. – William Pursell Jan 04 '20 at 16:53