首先说明一个跟变量比较相关的问题:
eg:
read readTest
if [ $readTest = "yes" ]
如果用户直接回车,将会报错 可能是[: =: Unary operator expected 这是为什么呢,因为对对readTest进行比较时, 它是一个空值
从而出现 if [ = "yes" ] 这不是个合法的条件,好方法就是
if [ "$readTest" = "yes" ]
//这样就算是空字符串,也是合法的了
if [ "" = "yes" ]
继续记录跟shell语法相关的
2.4 控制语句、
3)for语句
for variable in values
do
statements
done
eg:
#!/bin/sh
for boo in bar fud 43
do
echo $boo
done
exit0
这样将输出 bar fud 43
4) while 语句
while condition
do
statements
done
eg:
#!/bin/sh
echo "Enter password"
read trythis
while [ "$trythis" != "secret" ]; do
echo "Sorry, try again"
read trythis
done
echo "password is correct"
exit 0
until condition
do
statements
done
eg:
#!/bin/sh
until who | grep "$1" >/tmp/null
do
sleep 60
done
#now ring the bell and announce the expected user
echo -e '\a'
echo "*********$1 has juse logged in ********"
exit 0
case variable in
pattern [ |pattern] ...) statements;;
pattern [ |pattern] ...) statements;;
....
esac
eg1:
#!/bin/sh
echo "Is it morning? Please anser yes or no"
read timeofday
case "$timeofday" in
yes) echo "Good Morning";;
no ) echo "Good Afternoon";;
y ) echo "Good Morning";;
* ) echo "sorry, anser not recognized";;
esac
exit 0
#!/bin/sh
echo "Is it morning? Please anser yes or no"
read timeofday
case "$timeofday" in
yes | y | Yes | YES ) echo "Good Morning";;
n* |N*) echo "Good Afternoon";;
esac
exit 0
function_name () {
statements
}
eg1:
#!/bin/sh
foo() {
echo "Function foo is executing"
}
echo "scripot starting"
foo
echo "scripot ended"
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 "Anser yes or no";;
esac
done
}
echo "Original parameters are $*"
if yes_or_no "$1"
then
echo "Hi $1, nice name"
else
echo "Nerver mind"
fi
exit 0
$./my_name Rick NeilOriginal parameters are Rick Neil
Is your name Rick?
Enter yes or no: yes
Hi Rick,nice name
本次记录结束,下次继续记录Linux shell语法之命令