Linux学习笔记之一 ---Shell语法(2)

首先说明一个跟变量比较相关的问题:

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


5)until 语句

   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


6) case 语句

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


eg2

#!/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


2.5 函数

function_name () {
statements
}

eg1:

#!/bin/sh

foo() {
 echo "Function foo is executing"
}

echo "scripot starting"
foo
echo "scripot ended"

exit 0


eg2: 从函数中返回一个值
#!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 Neil
Original parameters are Rick Neil
Is your name Rick?
Enter yes or no: yes
Hi Rick,nice name


本次记录结束,下次继续记录Linux shell语法之命令


  








   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值