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

来源:互联网 发布:php curl 下载文件 编辑:程序博客网 时间:2024/06/18 13:13

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

eg:read readTestif [  $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/shfor boo in bar fud 43doecho $boodoneexit0
这样将输出 bar fud 43

4) while 语句

while condition 

do

statements

done

eg:

#!/bin/shecho "Enter password"read trythiswhile [ "$trythis" != "secret" ]; doecho "Sorry, try again"read trythisdoneecho "password is correct"exit 0


5)until 语句

   until condition
do
statements
done


eg:

#!/bin/shuntil who | grep "$1" >/tmp/nulldosleep 60done#now ring the bell and announce the expected userecho -e '\a'echo "*********$1 has juse logged in ********"exit 0


6) case 语句

case variable in
pattern [ |pattern] ...) statements;;
pattern [ |pattern] ...) statements;;
....
esac


eg1:

#!/bin/shecho "Is it morning? Please anser yes or no"read timeofdaycase "$timeofday" inyes) echo "Good Morning";;no ) echo "Good Afternoon";;y  ) echo "Good Morning";;*  ) echo "sorry, anser not recognized";;esacexit 0


eg2

#!/bin/shecho "Is it morning? Please anser yes or no"read timeofdaycase "$timeofday" inyes | y | Yes | YES ) echo "Good Morning";;n*  |N*)  echo "Good Afternoon";;esacexit 0


2.5 函数

function_name () {
statements
}

eg1:

#!/bin/shfoo() { echo "Function foo is executing"}echo "scripot starting"fooecho "scripot ended"exit 0


eg2: 从函数中返回一个值
#!bin/shyes_or_no() {echo "Is your name $* ?"while truedoecho -n "Enter yes or no:"read Xcase "$X" iny | yes ) return 0;;n | no  ) return 1;;*) echo "Anser yes or no";;esacdone}echo "Original parameters are $*"if yes_or_no "$1"thenecho "Hi $1, nice name"elseecho "Nerver mind"fiexit 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语法之命令


  








   

0 0
原创粉丝点击