In a bash script, using the conditional "or" in an "if" statement
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?
If you want to say OR
use double pipe (||
).
if [ "$fname" = "a.txt" ] || [ "$fname" = "c.txt" ]
(The original OP code using |
was simply piping the output of the left side to the right side, in the same way any ordinary pipe works.)
After many years of comments and misunderstanding, allow me to clarify.
To do OR
you use ||
.
Whether you use [
or [[
or test
or ((
all depends on what you need on a case by case basis. It’s wrong to say that one of those is preferred in all cases. Sometimes [
is right and [[
is wrong. But that’s not what the question was. OP asked why |
didn’t work. The answer is because it should be ||
instead.
You can use or condition like this
if [ "$fname" = "a.txt" -o "$fname" = "c.txt" ]
The accepted answer is good but since you’re using bash I’ll add the bash solution:
if [[ "$fname" == "a.txt" || "$fname" == "c.txt" ]]; then
This is documented in the bash reference manual 3.2.4.2 Conditional Constructs
expression1 && expression2
True if both expression1 and expression2 are true.
expression1 || expression2
True if either expression1 or expression2 is true.
The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.
You can also use OR condition like this
if test "$fname" = "a.txt" || test "$fname" = "c.txt"