结构化命令允许改变shell脚本的正常执行流程,最基础的结构化命令是if-then语句。该语句允许你评估命令并根据该命令的结果来执行其他命令。
if command
then
commands
else
commands
fi
#!/bin/bash
testuser=NoSuchUser
if grep $testuser /etc/passwd
then
echo "The scripts files in the home directory of the $testuser are:."
ls /home/$testuser/*.sh
echo
else
echo "The user $testuser does not exist on this system."
echo
fi
你也可以扩展if-then语句,加入一组当指定命令失败后由bash shell执行的命令。仅在测试命令返回非0退出状态码时,if-then-else语句才允许执行这些命令。
你还可以使用elif语句将多个if-then-else语句组合起来。elif等同于else if,会在测试命令失败时提供额外的检查。
if command1
then
commands
elif command2
then
more commands
fi
#!/bin/bash
testuser=NoSuchUser
if grep $testuser /etc/passwd
then
echo "The user $testuser account exists on this system."
echo
elif ls -d /home/$testuser/
then
echo "The user $testuser has a directory,"
echo "even though $testuser doesn't have an account"
fi
echo "we are outside the if statement"
在多数脚本中,你可能希望测试一种条件而不是命令,比如数值、字符串内容、文件或目录的状态,test命令为你提供了测试所有这些条件的简单方法。如果条件为真,test命令会为if-then语句产生退出状态码0.如果条件为假,test命令则会为if-then语句产生非0的退出状态码。
#!/bin/bash
if test
then
echo "No expression returns a True"
else
echo "No expression returns a False"
fi
方括号是与test命令同义的特殊bash命令。你可以在if-then语句中将测试条件放入方括号中来测试数值、字符串和文件条件。
if [ condition ]
then
command
fi
#!/bin/bash
string1=soccer
string2=zorbfootball
if [ $string1 \> $string2 ]
then
echo "$string1 is greater than $string2"
else
echo "$string1 is less than $string2"
fi
#!/bin/bash
# Check if a file is writable
#
item_name=$HOME/sentinel
echo
echo "Checking if you can write to $item_name..."
#
# Check if file exists and is a file.
#
if [ -f $item_name ]
then
# File does exist. Check if can write to it.
#
if [ -w $item_name ]
then
echo "Writing current time to $item_name"
date +%H%M >> $item_name
#
else
echo "Sorry, write access to $item_name is denied."
fi
#
else
echo "Sorry, the $item_name does not exist"
echo "or is not a file."
fi
双括号命令会使用另一批运算符执行高级数学运算。你可以在双方括号中进行字符串模式匹配。
#!/bin/bash
if [[ $BASH_VERSION == 4.* ]]
then
echo "you are using the Bash Shell version 4 series."
fi
最后,使用case命令可以优雅的代替执行多个if-then-else命令,它会参照一个值列表来检查单个变量的值。
#!/bin/bash
case $USER in
rich | christine)
echo "Welcome $USER"
echo "Please enjoy your visit";;
babarba | tim)
echo "Hi there,$USER"
echo "We're glad you could join us";;
testing)
echo "please log out when done with test";;
*)
echo "Sorry,you are not allowed here"
esac