I need to understand bash if expressions. Sure, I’ve used Google. I know that it goes something like this:
if [ expr operator expr ]
then
doSomeThing
fi
However, I understand that Bash doesn’t have a boolean data type. I want to check if the file passed as an argument ($1) exists. The way I would do this straight of my mind:
if [ -e $1 = true ]
then
echo "File exists."
fḯ
Or maybe like:
if [ -e $1 ] #Assuming that this is true only if file in $1 exists.
None of these work, and I’m not sure what [ ] means. -e $1 seems like a smart choice, but it is always true? There are different operators for strings and integers. And I can’t use parenthesis to group together expressions. This is so confusing.
Anyone got a few hints? The IF in bash does not work like if I’ve tried in any other language.
[ … ]
means that the program
/usr/bin/testgets executed with...as the arguments and its return value is checked (0meanstrueandx != 0meansfalse(yes,0really meanstruehere because0is theOKexit code in UNIX)). Sois correct. It’s the same as
The sole problem is that
$1could contain spaces. If so/usr/bin/testgets confused, since it gets 3 or more arguments. The first one (-e) is a unary operator (wants one argument). Since you gave it 2 or more (one/usr/bin/testargument is the-eitself), it complains like that:So, simply use
That will even work if
$1contains spaces. Another possibility is to useThat will do the same but it gets evaluated by bash itself and no
/usr/bin/testprogram gets forked.Compounds are as usual but
-ameansandand-omeansor. Sowill echo ok if
/etc/fstaband the file given as first command line argument exist.