Programmers: shell if is command
Published: LinuxQuestions
if command exit code is 0
then
do something 1
do something 2
fi
Example:
if cp fromfile tofile
then
echo "Works fine"
else
echo "Error ???"
fi
You can write test or [
test and [ is same command.
a=1
b=1
test "$a" = "$b"
echo $?
0
a=1
b=2
test "$a" = "$b"
echo $?
1
is same as
a=1
b=1
[ "$a" = "$b" ]
echo $?
0
a=1
b=2
[ "$a" = "$b" ]
echo $?
1
In some *nix systems test and [ are same binary. Bash, ksh, ... [ and test are built-in commands.
If you like to test command exit status, then it is possible with if.
a=1
b=1
if [ "$a" = "$b" ] ; then
echo "equal"
fi
# or
a=1
b=1
if test "$a" = "$b" ; then
echo "equal"
fi
You can write it also:
a=1
b=1
# - do test command and then check exit status
[ "$a" = "$b" ]
if [ $? = 0 ] ; then
echo "equal"
fi
Why ; before then ?
if and then on same line = you need
command delimeter ;
Remember
if is command which has arguments and options = space between every arguments.
Basic string testing
= equal
!= not equal
Basic numeric testing (options)
-eq equal
-ne not equal
-lt less than
-le less or equal
-gt greater than
-ge greater or equal
Basic file testing (options)
-f file exist
-d directory exist
-x execute priviledges
-r read ...
-w write ...
Negation !
if [ ! -f file ] ; then
echo "file $file not exists"
fi
if ! cp x y ; then
echo "error"
fi
And, or
-a and
-o or
if cp x y -a cp b z ; then
echo "noth copy done"
else
echo "co not worked
fi
if not like to see errors
if cp x y 2>/dev/null -a cp b z 2>/dev/null; then
echo "both copy done"
else
echo "cp not worked"
fi
&& ||
cp x y && cp a b || echo "error"
Is same as
if cp x y ; then
if ! cp a b ; then
echo "error"
fi
fi
&& if prev. exit stat 0, then this
|| if prev. exit stat <> 0, then this
Using variables
when use variables in test commands, use "". Why ? If variable is empty - you get error.
if [ "$a" = "" ] ; then
echo "empty"
exit
fi
If $a value is empty and you write
if [ $a = "" ] ; then
echo "empty"
exit
fi
you get error, because arg-1 is nothing.
"$a" is string, length 0
[[ ]] (( ))
[[ is not same as [
(( is for only numeric testing (C-like)
a=1
b=2
(( a>b )) && echo "$a > $b "
Remember: [ and test are same builtin command, but [[ is something
else, syntax is not
same.
I have used last 25 years only [ for string and file testing. I have learned to use (( for
numeric testing. You can use [ also for numeric testing, but syntax is different as in (( command. (( is more readable. My opinion.
Why I don't use [[ ? I have learned todo same special comparing using the excellent case command.
|