1、if-then语句格式:
if command
then
command
fi
----------------------------------------------------------------
if pwd
then
echo "It worked"
fi
还可以将then写到一行:
if command ; then
command
fi
2、if-then-else语句格式:
if command
then
command
else
command
fi
----------------------------------------------------------------
testuser=Christine
if grep $testuser /etc/passwd
then
echo "The bash files for user $testuser are:"
ls -a /home/$testuser/.b*
echo
else
echo "The user $testuser dose not exit on this system."
echo
fi
3、嵌套if格式:
if command
then
command
else
command
if command
then
command
fi
fi
4、多重if判断格式:
if command1
then
commands
elif command2
then
commands
fi
----------------------------------------------------------------
testuser=Christine
if grep $testuser /etc/passwd
then
echo "The user $testuser exists on this system."
#
elif ls -d /home/$testuser/
then
echo "The user $testuser dose not exist on this system."
echo "However, $testuser has a directory."
else
echo "The user $testuser dose not exist no this system."
echo "And, $testuser does not have a directory."
fi
5、if测试比较条件格式:
if [ condition]
then
commands
fi
if测试比较条件分类:数值比较、字符串比较、文件比较。
数字比较:
n1 -eq n2:n1 = n2
n1 -lt n2:n1 < n2
n1 -le n2:n1 <= n2
n1 -gt n2:n1 > n2
n1 -ge n2:n1 >= n2
n1 -ne n2:n1 != n2
例子:
value1=10
value2=11
#
if [ $value1 -gt 5 ]
then
echo "The test value $value1 is greater than 5"
fi
#
if [ $value1 -eq $value2 ]
then
echo "The values are equal"
else
echo "The values are different"
fi
字符串比较:
str1 = str2:检查str1和str2是否相同
str1 !=str2:检查str1和str2是否不同
str1 < str2:检查str1是否比str2小
str1 > str2:检查str1是否比str2大
-n str1:检查str1不为0
-z str2:检查str2是否为0
例子:
val1=Testing
val2=testing
#
if [ $val1 \> $val2 ]
then
echo "$val1 is greater than $val2"
else
echo "$val1 is less than $val2"
fi
文件比较:
-d file:检查file是否存在并且是个目录
-e file:检查file是否存在
-f file:检查file是否存在并且是个文件
-r file:检查file是否存在并且可读
-s file:检查文件是否在并且不为空
-w file:检查file是否存在并且可写
-x file:检查file是否存在并且可执行
-O file:检查file是否存在并且属于当前用户
-G file:检查file是否存在并且默认组与当前用户组相同
file1 -nt file2:file1是否比file2新
file1 -ot file2:file1是否比file2旧
例子:
jump_directory=/home/arthur
#
if [ -d $jump_directory ]
then
echo "The $jump_directory directory exists"
cd $jump_directory
ls
else
echo "The $jump_directory directory does not exists"
fi
6、逻辑条件测试:
[ condition1 ] && [ condition2 ]:相当于and
[ condition1 ] || [ condition2 ]:相当于or
7、使用双括号:提供了更多的数学符号,在这里面运算符不需要转义
(( expression ))
例子:
val1=10
#
if (( $val1 ** 2 > 90 ))
then
(( val2 = $val1 ** 2 ))
echo "The square of $val1 is $val2"
fi
8、使用双方括号:提供了模式匹配
[[ expression ]]
例子:
if [[ $USER == r* ]]
then
echo "Hello $USER"
else
echo "Sorry, I do not know you"
fi
9、case命令结构:
case var in
a)
commands
;;
b)
commands
;;
esac
例子:
case $USER in
rich | barbara)
echo "Welcome, $USER"
echo "Please enjoy your visit"
;;
testing)
echo "Special testing account"
;;
jessica)
echo "Do not forget to log off when you're done"
;;
*)
echo "Sorry, you are not allowed here"
;;
esac