Shell自己是一个用C语言编写的程序,它是用户使用Unix/Linux的桥梁,用户的大部分工做都是经过Shell完成的。Shell既是一种命令语言,又是一种程序设计语言。做为命令语言,它交互式地解释和执行用户输入的命令;做为程序设计语言,它定义了各类变量和参数,并提供了许多在高级语言中才具备的控制结构,包括循环和分支。php
它虽然不是Unix/Linux系统内核的一部分,但它调用了系统核心的大部分功能来执行程序、创建文件并以并行的方式协调各个程序的运行。所以,对于用户来讲,shell是最重要的实用程序,深刻了解和熟练掌握shell的特性极其使用方法,是用好Unix/Linux系统的关键。html
能够说,shell使用的熟练程度反映了用户对Unix/Linux使用的熟练程度。linux
注意:单独地学习 Shell 是没有意义的,请先参考Unix/Linux入门教程,了解 Unix/Linux 基础。ios
Shell有两种执行命令的方式:git
交互式(Interactive):解释执行用户的命令,用户输入一条命令,Shell就解释执行一条。github
批处理(Batch):用户事先写一个Shell脚本(Script),其中有不少条命令,让Shell一次把这些命令执行完,而没必要一条一条地敲命令。web
Shell脚本和编程语言很类似,也有变量和流程控制语句,但Shell脚本是解释执行的,不须要编译,Shell程序从脚本中一行一行读取并执行这些命令,至关于一个用户把脚本中的命令一行一行敲到Shell提示符下执行。shell
Shell初学者请注意,在日常应用中,建议不要用 root 账号运行 Shell 。做为普通用户,无论您有意仍是无心,都没法破坏系统;但若是是 root,那就不一样了,只要敲几个字母,就可能致使灾难性后果。express
bash:bash是Linux标准默认的shell,本教程也基于bash讲解。bash由Brian Fox和Chet Ramey共同完成,是BourneAgain Shell的缩写,内部命令一共有40个。编程
Linux使用它做为默认的shell是由于它有诸如如下的特点:
可使用相似DOS下面的doskey的功能,用方向键查阅和快速输入并修改命令。
自动经过查找匹配的方式给出以某字符串开头的命令。
包含了自身的帮助功能,你只要在提示符下面键入help就能够获得相关的帮助。
sh:sh 由Steve Bourne开发,是Bourne Shell的缩写,sh 是Unix 标准默认的shell。
ash:ash shell 是由Kenneth Almquist编写的,Linux中占用系统资源最少的一个小shell,它只包含24个内部命令,于是使用起来很不方便。
csh:csh 是Linux比较大的内核,它由以William Joy为表明的共计47位做者编成,共有52个内部命令。该shell实际上是指向/bin/tcsh这样的一个shell,也就是说,csh其实就是tcsh。
ksh:ksh 是Korn shell的缩写,由Eric Gisin编写,共有42条内部命令。该shell最大的优势是几乎和商业发行版的ksh彻底兼容,这样就能够在不用花钱购买商业版本的状况下尝试商业版本的性能了。
注意:bash是 Bourne Again Shell 的缩写,是linux标准的默认shell ,它基于Bourne shell,吸取了C shell和Korn shell的一些特性。bash彻底兼容sh,也就是说,用sh写的脚本能够不加修改的在bash中执行。#!/bin/bash echo "Hello World !"
将上面的代码保存为test.sh,并 cd 到相应目录:
chmod +x ./test.sh #使脚本具备执行权限 ./test.sh #执行脚本
/bin/sh test.sh
/bin/php test.php
#!/bin/bash # Author : mozhiyan # Copyright (c) http://see.xidian.edu.cn/cpp/linux/ # Script follows here: echo "What is your name?" read PERSON echo "Hello, $PERSON"
chmod +x ./test.sh $./test.sh What is your name? mozhiyan Hello, mozhiyan
variableName="value"
myUrl="http://see.xidian.edu.cn/cpp/linux/" myNum=100
your_name="mozhiyan" echo $your_name echo ${your_name}
for skill in Ada Coffe Action Java do echo "I am good at ${skill}Script" done
myUrl="http://see.xidian.edu.cn/cpp/linux/" echo ${myUrl} myUrl="http://see.xidian.edu.cn/cpp/shell/" echo ${myUrl}
#!/bin/bash myUrl="http://see.xidian.edu.cn/cpp/shell/" readonly myUrl myUrl="http://see.xidian.edu.cn/cpp/danpianji/"
/bin/sh: NAME: This variable is read only.
unset variable_name
#!/bin/sh myUrl="http://see.xidian.edu.cn/cpp/u/xitong/" unset myUrl echo $myUrl
$echo $$
变量 | 含义 |
---|---|
$0 | 当前脚本的文件名 |
$n | 传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。 |
$# | 传递给脚本或函数的参数个数。 |
$* | 传递给脚本或函数的全部参数。 |
$@ | 传递给脚本或函数的全部参数。被双引号(" ")包含时,与 $* 稍有不一样,下面将会讲到。 |
$? | 上个命令的退出状态,或函数的返回值。 |
$$ | 当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。 |
#!/bin/bash echo "File Name: $0" echo "First Parameter : $1" echo "First Parameter : $2" echo "Quoted Values: $@" echo "Quoted Values: $*" echo "Total Number of Parameters : $#"
$./test.sh Zara Ali File Name : ./test.sh First Parameter : Zara Second Parameter : Ali Quoted Values: Zara Ali Quoted Values: Zara Ali Total Number of Parameters : 2
#!/bin/bash echo "\$*=" $* echo "\"\$*\"=" "$*" echo "\$@=" $@ echo "\"\$@\"=" "$@" echo "print each param from \$*" for var in $* do echo "$var" done echo "print each param from \$@" for var in $@ do echo "$var" done echo "print each param from \"\$*\"" for var in "$*" do echo "$var" done echo "print each param from \"\$@\"" for var in "$@" do echo "$var"
$*= a b c d "$*"= a b c d $@= a b c d "$@"= a b c d print each param from $* a b c d print each param from $@ a b c d print each param from "$*" a b c d print each param from "$@" a b c d
$./test.sh Zara Ali File Name : ./test.sh First Parameter : Zara Second Parameter : Ali Quoted Values: Zara Ali Quoted Values: Zara Ali Total Number of Parameters : 2 $echo $? 0 $
#!/bin/bash a=10 echo -e "Value of a is $a \n"
Value of a is 10
Value of a is 10\n
转义字符 | 含义 |
---|---|
\\ | 反斜杠 |
\a | 警报,响铃 |
\b | 退格(删除键) |
\f | 换页(FF),将当前位置移到下页开头 |
\n | 换行 |
\r | 回车 |
\t | 水平制表符(tab键) |
\v | 垂直制表符 |
`command`
#!/bin/bash DATE=`date` echo "Date is $DATE" USERS=`who | wc -l` echo "Logged in user are $USERS" UP=`date ; uptime` echo "Uptime is $UP"
Date is Thu Jul 2 03:59:57 MST 2009 Logged in user are 1 Uptime is Thu Jul 2 03:59:57 MST 2009 03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15
形式 | 说明 |
---|---|
${var} | 变量原本的值 |
${var:-word} | 若是变量 var 为空或已被删除(unset),那么返回 word,但不改变 var 的值。 |
${var:=word} | 若是变量 var 为空或已被删除(unset),那么返回 word,并将 var 的值设置为 word。 |
${var:?message} | 若是变量 var 为空或已被删除(unset),那么将消息 message 送到标准错误输出,能够用来检测变量 var 是否能够被正常赋值。 若此替换出如今Shell脚本中,那么脚本将中止运行。 |
${var:+word} | 若是变量 var 被定义,那么返回 word,但不改变 var 的值。 |
#!/bin/bash echo ${var:-"Variable is not set"} echo "1 - Value of var is ${var}" echo ${var:="Variable is not set"} echo "2 - Value of var is ${var}" unset var echo ${var:+"This is default value"} echo "3 - Value of var is $var" var="Prefix" echo ${var:+"This is default value"} echo "4 - Value of var is $var" echo ${var:?"Print this message"} echo "5 - Value of var is ${var}"
Variable is not set 1 - Value of var is Variable is not set 2 - Value of var is Variable is not set 3 - Value of var is This is default value 4 - Value of var is Prefix Prefix 5 - Value of var is Prefix
#!/bin/bash val=`expr 2 + 2` echo "Total value : $val"
Total value : 4
#!/bin/sh a=10 b=20 val=`expr $a + $b` echo "a + b : $val" val=`expr $a - $b` echo "a - b : $val" val=`expr $a \* $b` echo "a * b : $val" val=`expr $b / $a` echo "b / a : $val" val=`expr $b % $a` echo "b % a : $val" if [ $a == $b ] then echo "a is equal to b" fi if [ $a != $b ] then echo "a is not equal to b" fi
a + b : 30 a - b : -10 a * b : 200 b / a : 2 b % a : 0 a is not equal to b
运算符 | 说明 | 举例 |
---|---|---|
+ | 加法 | `expr $a + $b` 结果为 30。 |
- | 减法 | `expr $a - $b` 结果为 10。 |
* | 乘法 | `expr $a \* $b` 结果为 200。 |
/ | 除法 | `expr $b / $a` 结果为 2。 |
% | 取余 | `expr $b % $a` 结果为 0。 |
= | 赋值 | a=$b 将把变量 b 的值赋给 a。 |
== | 相等。用于比较两个数字,相同则返回 true。 | [ $a == $b ] 返回 false。 |
!= | 不相等。用于比较两个数字,不相同则返回 true。 | [ $a != $b ] 返回 true。 |
#!/bin/sh a=10 b=20 if [ $a -eq $b ] then echo "$a -eq $b : a is equal to b" else echo "$a -eq $b: a is not equal to b" fi if [ $a -ne $b ] then echo "$a -ne $b: a is not equal to b" else echo "$a -ne $b : a is equal to b" fi if [ $a -gt $b ] then echo "$a -gt $b: a is greater than b" else echo "$a -gt $b: a is not greater than b" fi if [ $a -lt $b ] then echo "$a -lt $b: a is less than b" else echo "$a -lt $b: a is not less than b" fi if [ $a -ge $b ] then echo "$a -ge $b: a is greater or equal to b" else echo "$a -ge $b: a is not greater or equal to b" fi if [ $a -le $b ] then echo "$a -le $b: a is less or equal to b" else echo "$a -le $b: a is not less or equal to b" fi
10 -eq 20: a is not equal to b 10 -ne 20: a is not equal to b 10 -gt 20: a is not greater than b 10 -lt 20: a is less than b 10 -ge 20: a is not greater or equal to b 10 -le 20: a is less or equal to b
运算符 | 说明 | 举例 |
---|---|---|
-eq | 检测两个数是否相等,相等返回 true。 | [ $a -eq $b ] 返回 true。 |
-ne | 检测两个数是否相等,不相等返回 true。 | [ $a -ne $b ] 返回 true。 |
-gt | 检测左边的数是否大于右边的,若是是,则返回 true。 | [ $a -gt $b ] 返回 false。 |
-lt | 检测左边的数是否小于右边的,若是是,则返回 true。 | [ $a -lt $b ] 返回 true。 |
-ge | 检测左边的数是否大等于右边的,若是是,则返回 true。 | [ $a -ge $b ] 返回 false。 |
-le | 检测左边的数是否小于等于右边的,若是是,则返回 true。 | [ $a -le $b ] 返回 true。 |
#!/bin/sh a=10 b=20 if [ $a != $b ] then echo "$a != $b : a is not equal to b" else echo "$a != $b: a is equal to b" fi if [ $a -lt 100 -a $b -gt 15 ] then echo "$a -lt 100 -a $b -gt 15 : returns true" else echo "$a -lt 100 -a $b -gt 15 : returns false" fi if [ $a -lt 100 -o $b -gt 100 ] then echo "$a -lt 100 -o $b -gt 100 : returns true" else echo "$a -lt 100 -o $b -gt 100 : returns false" fi if [ $a -lt 5 -o $b -gt 100 ] then echo "$a -lt 100 -o $b -gt 100 : returns true" else echo "$a -lt 100 -o $b -gt 100 : returns false" fi
10 != 20 : a is not equal to b 10 -lt 100 -a 20 -gt 15 : returns true 10 -lt 100 -o 20 -gt 100 : returns true 10 -lt 5 -o 20 -gt 100 : returns false
运算符 | 说明 | 举例 |
---|---|---|
! | 非运算,表达式为 true 则返回 false,不然返回 true。 | [ ! false ] 返回 true。 |
-o | 或运算,有一个表达式为 true 则返回 true。 | [ $a -lt 20 -o $b -gt 100 ] 返回 true。 |
-a | 与运算,两个表达式都为 true 才返回 true。 | [ $a -lt 20 -a $b -gt 100 ] 返回 false。 |
#!/bin/sh a="abc" b="efg" if [ $a = $b ] then echo "$a = $b : a is equal to b" else echo "$a = $b: a is not equal to b" fi if [ $a != $b ] then echo "$a != $b : a is not equal to b" else echo "$a != $b: a is equal to b" fi if [ -z $a ] then echo "-z $a : string length is zero" else echo "-z $a : string length is not zero" fi if [ -n $a ] then echo "-n $a : string length is not zero" else echo "-n $a : string length is zero" fi if [ $a ] then echo "$a : string is not empty" else echo "$a : string is empty" fi
abc = efg: a is not equal to b abc != efg : a is not equal to b -z abc : string length is not zero -n abc : string length is not zero abc : string is not empty
运算符 | 说明 | 举例 |
---|---|---|
= | 检测两个字符串是否相等,相等返回 true。 | [ $a = $b ] 返回 false。 |
!= | 检测两个字符串是否相等,不相等返回 true。 | [ $a != $b ] 返回 true。 |
-z | 检测字符串长度是否为0,为0返回 true。 | [ -z $a ] 返回 false。 |
-n | 检测字符串长度是否为0,不为0返回 true。 | [ -z $a ] 返回 true。 |
str | 检测字符串是否为空,不为空返回 true。 | [ $a ] 返回 true。 |
#!/bin/sh file="/var/www/tutorialspoint/unix/test.sh" if [ -r $file ] then echo "File has read access" else echo "File does not have read access" fi if [ -w $file ] then echo "File has write permission" else echo "File does not have write permission" fi if [ -x $file ] then echo "File has execute permission" else echo "File does not have execute permission" fi if [ -f $file ] then echo "File is an ordinary file" else echo "This is sepcial file" fi if [ -d $file ] then echo "File is a directory" else echo "This is not a directory" fi if [ -s $file ] then echo "File size is zero" else echo "File size is not zero" fi if [ -e $file ] then echo "File exists" else echo "File does not exist" fi
File has read access File has write permission File has execute permission File is an ordinary file This is not a directory File size is zero File exists
操做符 | 说明 | 举例 |
---|---|---|
-b file | 检测文件是不是块设备文件,若是是,则返回 true。 | [ -b $file ] 返回 false。 |
-c file | 检测文件是不是字符设备文件,若是是,则返回 true。 | [ -b $file ] 返回 false。 |
-d file | 检测文件是不是目录,若是是,则返回 true。 | [ -d $file ] 返回 false。 |
-f file | 检测文件是不是普通文件(既不是目录,也不是设备文件),若是是,则返回 true。 | [ -f $file ] 返回 true。 |
-g file | 检测文件是否设置了 SGID 位,若是是,则返回 true。 | [ -g $file ] 返回 false。 |
-k file | 检测文件是否设置了粘着位(Sticky Bit),若是是,则返回 true。 | [ -k $file ] 返回 false。 |
-p file | 检测文件是不是具名管道,若是是,则返回 true。 | [ -p $file ] 返回 false。 |
-u file | 检测文件是否设置了 SUID 位,若是是,则返回 true。 | [ -u $file ] 返回 false。 |
-r file | 检测文件是否可读,若是是,则返回 true。 | [ -r $file ] 返回 true。 |
-w file | 检测文件是否可写,若是是,则返回 true。 | [ -w $file ] 返回 true。 |
-x file | 检测文件是否可执行,若是是,则返回 true。 | [ -x $file ] 返回 true。 |
-s file | 检测文件是否为空(文件大小是否大于0),不为空返回 true。 | [ -s $file ] 返回 true。 |
-e file | 检测文件(包括目录)是否存在,若是是,则返回 true。 | [ -e $file ] 返回 true。 |
#-------------------------------------------- # 这是一个自动打ipa的脚本,基于webfrogs的ipa-build书写: # https://github.com/webfrogs/xcode_shell/blob/master/ipa-build # 功能:自动为etao ios app打包,产出物为14个渠道的ipa包 # 特点:全自动打包,不须要输入任何参数 #-------------------------------------------- ##### 用户配置区 开始 ##### # # # 项目根目录,推荐将此脚本放在项目的根目录,这里就不用改了 # 应用名,确保和Xcode里Product下的target_name.app名字一致 # ##### 用户配置区 结束 #####
str='this is a string'
your_name='qinjx' str="Hello, I know your are \"$your_name\"! \n"
your_name="qinjx" greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1
string="abcd" echo ${#string} #输出 4
string="alibaba is a great company" echo ${string:1:4} #输出liba
string="alibaba is a great company" echo `expr index "$string" is`
array_name=(value0 value1 value2 value3)
array_name=(
value0
value1
value2
value3
)
array_name[0]=value0 array_name[1]=value1 array_name[2]=value2
valuen=${array_name[2]}
#!/bin/sh NAME[0]="Zara" NAME[1]="Qadir" NAME[2]="Mahnaz" NAME[3]="Ayan" NAME[4]="Daisy" echo "First Index: ${NAME[0]}" echo "Second Index: ${NAME[1]}"
$./test.sh
First Index: Zara
Second Index: Qadir
${array_name[*]}
${array_name[@]}
#!/bin/sh NAME[0]="Zara" NAME[1]="Qadir" NAME[2]="Mahnaz" NAME[3]="Ayan" NAME[4]="Daisy" echo "First Method: ${NAME[*]}" echo "Second Method: ${NAME[@]}"
$./test.sh
First Method: Zara Qadir Mahnaz Ayan Daisy
Second Method: Zara Qadir Mahnaz Ayan Daisy
# 取得数组元素的个数 length=${#array_name[@]} # 或者 length=${#array_name[*]} # 取得数组单个元素的长度 lengthn=${#array_name[n]}
echo arg
echo "\"It is a test\""
"It is a test"
name="OK" echo "$name It is a test"
OK It is a test
mouth=8 echo "${mouth}-1-2009"
8-1-2009
echo "OK!\n" echo "It is a test"
OK! It is a test
echo "OK!\c" echo "It is a test"
OK!It si a test
echo "It is a test" > myfile
echo '$name\"'
echo `date`
$printf "Hello, Shell\n" Hello, Shell $
printf format-string [arguments...]
# format-string为双引号 $ printf "%d %s\n" 1 "abc" 1 abc # 单引号与双引号效果同样 $ printf '%d %s\n' 1 "abc" 1 abc # 没有引号也能够输出 $ printf %s abcdef abcdef # 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用 $ printf %s abc def abcdef $ printf "%s\n" abc def abc def $ printf "%s %s %s\n" a b c d e f g h i j a b c d e f g h i j # 若是没有 arguments,那么 %s 用NULL代替,%d 用 0 代替 $ printf "%s and %d \n" and 0 # 若是以 %d 的格式来显示字符串,那么会有警告,提示无效的数字,此时默认置为 0 $ printf "The first program always prints'%s,%d\n'" Hello Shell -bash: printf: Shell: invalid number The first program always prints 'Hello,0' $
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
若是 expression 返回 true,then 后边的语句将会被执行;若是返回 false,不会执行任何语句。
#!/bin/sh a=10 b=20 if [ $a == $b ] then echo "a is equal to b" fi if [ $a != $b ] then echo "a is not equal to b" fi
a is not equal to b
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
若是 expression 返回 true,那么 then 后边的语句将会被执行;不然,执行 else 后边的语句。
#!/bin/sh a=10 b=20 if [ $a == $b ] then echo "a is equal to b" else echo "a is not equal to b" fi
a is not equal to b
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
哪个 expression 的值为 true,就执行哪一个 expression 后面的语句;若是都为 false,那么不执行任何语句。
#!/bin/sh a=10 b=20 if [ $a == $b ] then echo "a is equal to b" elif [ $a -gt $b ] then echo "a is greater than b" elif [ $a -lt $b ] then echo "a is less than b" else echo "None of the condition met" fi
a is less than b
if ... else 语句也能够写成一行,以命令的方式来运行,像这样:
if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;
num1=$[2*3] num2=$[1+5] if test $[num1] -eq $[num2] then echo 'The two numbers are equal!' else echo 'The two numbers are not equal!' fi
The two numbers are equal!
模式1)
command1
command2
command3
;;
模式2)
command1
command2
command3
;;
*)
command1
command2
command3
;;
esac
case工做方式如上所示。取值后面必须为关键字 in,每一模式必须以右括号结束。取值能够为变量或常数。匹配发现取值符合某一模式后,其间全部命令开始执行直至 ;;。;; 与其余语言中的 break 相似,意思是跳到整个 case 语句的最后。
echo 'Input a number between 1 to 4' echo 'Your number is:\c' read aNum case $aNum in 1) echo 'You select 1' ;; 2) echo 'You select 2' ;; 3) echo 'You select 3' ;; 4) echo 'You select 4' ;; *) echo 'You do not select a number between 1 to 4' ;; esac
Input a number between 1 to 4 Your number is:3 You select 3
#!/bin/bash option="${1}" case ${option} in -f) FILE="${2}" echo "File name is $FILE" ;; -d) DIR="${2}" echo "Dir name is $DIR" ;; *) echo "`basename ${0}`:usage: [-f file] | [-d directory]" exit 1 # Command to come out of the program with status 1 ;; esac
$./test.sh test.sh: usage: [ -f filename ] | [ -d directory ] $ ./test.sh -f index.htm $ vi test.sh $ ./test.sh -f index.htm File name is index.htm $ ./test.sh -d unix Dir name is unix $
for 变量 in 列表
do
command1
command2
...
commandN
done
列表是一组值(数字、字符串等)组成的序列,每一个值经过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
for loop in 1 2 3 4 5 do echo "The value is: $loop" done
The value is: 1 The value is: 2 The value is: 3 The value is: 4 The value is: 5
for str in 'This is a string' do echo $str done
This is a string
#!/bin/bash for FILE in $HOME/.bash* do echo $FILE done
/root/.bash_history /root/.bash_logout /root/.bash_profile /root/.bashrc
while command
do
Statement(s) to be executed if command is true
done
命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。
COUNTER=0 while [ $COUNTER -lt 5 ] do COUNTER='expr $COUNTER+1' echo $COUNTER done
1 2 3 4 5
echo 'type <CTRL-D> to terminate' echo -n 'enter your most liked film: ' while read FILM do echo "Yeah! great film the $FILM" done
type <CTRL-D> to terminate
enter your most liked film: Sound of Music
Yeah! great film the Sound of Music
until command
do
Statement(s) to be executed until command is true
done
command 通常为条件表达式,若是返回值为 false,则继续执行循环体内的语句,不然跳出循环。
#!/bin/bash a=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done
0
1
2
3
4
5
6
7
8
9
#!/bin/bash while : do echo -n "Input a number between 1 to 5: " read aNum case $aNum in 1|2|3|4|5) echo "Your number is $aNum!" ;; *) echo "You do not select a number between 1 to 5, game is over!" break ;; esac done
break n
#!/bin/bash for var1 in 1 2 3 do for var2 in 0 5 do if [ $var1 -eq 2 -a $var2 -eq 0 ] then break 2 else echo "$var1 $var2" fi done done
1 0
1 5
#!/bin/bash while : do echo -n "Input a number between 1 to 5: " read aNum case $aNum in 1|2|3|4|5) echo "Your number is $aNum!" ;; *) echo "You do not select a number between 1 to 5!" continue echo "Game is over!" ;; esac done
echo "Game is over!"
#!/bin/bash NUMS="1 2 3 4 5 6 7" for NUM in $NUMS do Q=`expr $NUM % 2` if [ $Q -eq 0 ] then echo "Number is an even number!!" continue fi echo "Found odd number" done
Found odd number Number is an even number!! Found odd number Number is an even number!! Found odd number Number is an even number!! Found odd number
function_name () {
list of commands
[ return value ]
}
若是你愿意,也能够在函数名前加上关键字 function:
function function_name () {
list of commands
[ return value ]
}
函数返回值,能够显式增长return语句;若是不加,会将最后一条命令运行结果做为返回值。
#!/bin/bash # Define your function here Hello () { echo "Url is http://see.xidian.edu.cn/cpp/shell/" } # Invoke your function Hello
$./test.sh
Hello World
$
#!/bin/bash funWithReturn(){ echo "The function is to get the sum of two numbers..." echo -n "Input first number: " read aNum echo -n "Input another number: " read anotherNum echo "The two numbers are $aNum and $anotherNum !" return $(($aNum+$anotherNum)) } funWithReturn # Capture value returnd by last command ret=$? echo "The sum of two numbers is $ret !"
The function is to get the sum of two numbers... Input first number: 25 Input another number: 50 The two numbers are 25 and 50 ! The sum of two numbers is 75 !
#!/bin/bash # Calling one function from another number_one () { echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/" number_two } number_two () { echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/" } number_one
Url_1 is http://see.xidian.edu.cn/cpp/shell/ Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/
$unset .f function_name
#!/bin/bash funWithParam(){ echo "The value of the first parameter is $1 !" echo "The value of the second parameter is $2 !" echo "The value of the tenth parameter is $10 !" echo "The value of the tenth parameter is ${10} !" echo "The value of the eleventh parameter is ${11} !" echo "The amount of the parameters is $# !" # 参数个数 echo "The string of the parameters is $* !" # 传递给函数的全部参数 } funWithParam 1 2 3 4 5 6 7 8 9 34 73
The value of the first parameter is 1 ! The value of the second parameter is 2 ! The value of the tenth parameter is 10 ! The value of the tenth parameter is 34 ! The value of the eleventh parameter is 73 ! The amount of the parameters is 12 ! The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"
特殊变量 | 说明 |
---|---|
$# | 传递给函数的参数个数。 |
$* | 显示全部传递给函数的参数。 |
$@ | 与$*相同,可是略有区别,请查看Shell特殊变量。 |
$? | 函数的返回值。 |
$ command > file
$ who > users
$ cat users oko tty01 Sep 12 07:30 ai tty15 Sep 12 13:32 ruth tty21 Sep 12 10:10 pat tty24 Sep 12 13:07 steve tty25 Sep 12 13:03 $
$ echo line 1 > users $ cat users line 1 $
$ echo line 2 >> users $ cat users line 1 line 2 $
command < file
$ wc -l users 2 users $
$ wc -l < users 2 $
$command 2 > file
$command 2 >> file
$command > file 2>&1
$command >> file 2>&1
$command < file1 >file2
命令 | 说明 |
---|---|
command > file | 将输出重定向到 file。 |
command < file | 将输入重定向到 file。 |
command >> file | 将输出以追加的方式重定向到 file。 |
n > file | 将文件描述符为 n 的文件重定向到 file。 |
n >> file | 将文件描述符为 n 的文件以追加的方式重定向到 file。 |
n >& m | 将输出文件 m 和 n 合并。 |
n <& m | 将输入文件 m 和 n 合并。 |
<< tag | 将开始标记 tag 和结束标记 tag 之间的内容做为输入。 |
$wc -l << EOF This is a simple lookup program for good (and bad) restaurants in Cape Town. EOF 3 $
#!/bin/bash cat << EOF This is a simple lookup program for good (and bad) restaurants in Cape Town. EOF
This is a simple lookup program for good (and bad) restaurants in Cape Town.
#!/bin/sh filename=test.txt vi $filename <<EndOfCommands i This file was created automatically from a shell script ^[ ZZ EndOfCommands
$ sh test.sh Vim: Warning: Input is not from a terminal $
$ cat test.txt This file was created automatically from a shell script $
$ command > /dev/null
$ command > /dev/null 2>&1
. filename
source filename
url="http://see.xidian.edu.cn/cpp/view/2738.html"
#!/bin/bash . ./subscript.sh echo $url
$chomd +x main.sh ./main.sh http://see.xidian.edu.cn/cpp/view/2738.html $