1.命令列表
有时,我们想要将几条命令连接成一个序列。
if [ -f this_file ] ; then
if [ -f that_file ] ; then
if [ -f the_othe_file ] ; then
echo "All files present,and correct"
fi
fi
fi
这样写非常笨拙。shell提供了一对特殊的结构,专门用于处理命令列表,它们分别是:AND列表和OR列表。
AND列表 的语法:
statement1 && statement2 && statement3 && ....
OR 列表:
OR列表结构允许我们持续执行一系列命令知道一条命令成功为止,它们的语法:
statement1 || statement2 || statement3 || ....
2.函数
要定义一个shell函数,我们只需简单地写出它的名字,然后是一对空括号,再把有关的语句放在一对花括号中
function_name () {
statements
}
可以通过return命令让函数返回数字值,让函数返回字符串值的常用方法是让函数将字符串保存在一个变量中,而该变量应该可以在杉树结束之后被使用。
foo () { echo JAY;}
....
result="$(foo)"
#!/bin/sh
sample_text="global variable"
foo() {
local sample_text="local variable"
echo "Function foo is executing"
echo $sample_text
}
echo "script starting"
echo $sample_text
foo
echo "script_ended"
echo $sample_text
exit 0
#!/bin/sh
yes_or_no() {
echo "Is your name $* ?"
while true
do
echo -n "Enter yes or no:"
read x
case "$x" in
y | yes ) return 0;;
n | no ) return 1;;
* ) echo "Answer yes or not"
esac
done
}
echo "Original parametera are $*"
if yes_or_no "$1"
then
echo "Hi $1,nice name"
else
echo "Never mind"
fi
exit 0