shell script to sort out the basics <three>: test conditions and comparison process control if

First, the conditions of the test with Comparative
1, test expressions are used to test
Test File -f && echo echo to false to true ||
2, [Expression test] particularly common
[-f File] && || echo echo to true to false
. 3, [[Test expression]]
Second, the process control

1, if the flow control statements
Example 1
! # / Bin / the bash
# Get uid = 0 (root) is 0;
ID =id | awk -F '[=(]' '{print $2}'
echo "User ID your IS: $ ID"
if [$ ID -eq 0]
the then
echo "the root "
the else
echo" Not the root "
Fi
example 2: Analyzing logged in user
# / bin / the bash!
# $ # shell is added to the number of parameters
if [$ # -eq 1] # or [[$ # == 1]] or (($ # ==. 1))
the then
IF WHO | grep $. 1> / dev / null
the then
echo $. 1 IS Active.
the else
echo $. 1 IS Not Active.
Fi
the else
echo "the Usage: $ 0 <username>"
Exit. 1
Fi
~
executed the result of
[root @ localhost shell] # SH if-if.sh root
root iS the Active.
[root @ localhost shell] # SH if-if.sh zabbix
zabbix is not active.
[root@localhost shell]# sh if-if.sh
Usage: if-if.sh <username>
[root@localhost shell]#
实例3 if-elif..else-fi
#!/bin/bash
##if-elif..else-fi
read -p "how lod are you? " age
#使用shell算数运算符(())进行条件测试
if ((age<0||age>120));then #[[ age < 0 || age > 120 ]]
echo "out of range !"
exit 1
fi
if ((age>=0&&age<13));then
echo "child!"
elif ((age>=13&&age<20));then
echo "callan!"
elif ((age>=20&&age<30));then
echo "P iii"
elif ((age>=30&&age<40));then
echo "P IV I"
else
echo "Sorry I asked."
fi
实例4
#!/bin/bash
## if statements can be nested
File. 1 = $
[$ # -ne 1] && echo "Usage: $ 0 <filename >" Exit. 1 &&
# error wording [$ # -ne 1] && echo "Usage: $ 0 <filename > "; exit 1 so"; "No matter whether in front of the judge will perform the correct
line
iF [-d $ File]
the then
echo" $ iS a File Directory "
elif [-f $ File]
the then
iF [-r -a $ File the -X-File $ $ -a -w File]; the then
echo. "you have have (rwx) permissioon File $ ON"
the else
. "IS $ File File" echo
Fi
the else
echo "$ FLES neither IS A NOR A Directory File."
fi
execution result
[the shell the root @ localhost] # Vim if-elif-if-else.sh
[the shell the root @ localhost] # SH-IF-IF-elif the else.sh liu
you have (rwx) permissioon on liu.
[root@localhost shell]# sh if-elif-if-else.sh liub
liub is a directory
[root@localhost shell]# touch qq
[root@localhost shell]# sh if-elif-if-else.sh qq
qq is file.
[root@localhost shell]#

Guess you like

Origin blog.51cto.com/14294148/2434481