Shell

来源:互联网 发布:久坐肚子大 知乎 编辑:程序博客网 时间:2024/06/02 05:06

一、Shell 变量

定义变量不加“$”,使用变量是添加"$"符号

your_name="mozhiyan"echo $your_nameecho ${your_name}

只读变量:

<span style="font-size:14px;">readonly myUrl</span>


删除变量:

<span style="font-size:14px;">unset variable_name</span>

二、Shell特殊变量


特殊变量列表变量含义$0当前脚本的文件名$n传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。$#传递给脚本或函数的参数个数。$*传递给脚本或函数的所有参数。$@传递给脚本或函数的所有参数。被双引号(" ")包含时,与 $* 稍有不同,下面将会讲到。$?上个命令的退出状态,或函数的返回值。$$当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。例子:
<span style="font-size:14px;">#!/bin/bashecho "File Name: $0"echo "First Parameter : $1"echo "First Parameter : $2"echo "Quoted Values: $@"echo "Quoted Values: $*"echo "Total Number of Parameters : $#"</span>
结果
<span style="font-size:14px;">$./test.sh Zara AliFile Name : ./test.shFirst Parameter : ZaraSecond Parameter : AliQuoted Values: Zara AliQuoted Values: Zara AliTotal Number of Parameters : 2</span>


$@和$*的区别:

但是当它们被双引号(" ")包含时,"$*" 会将所有的参数作为一个整体,以"$1 $2 … $n"的形式输出所有参数;"$@" 会将各个参数分开,以"$1" "$2" … "$n" 的形式输出所有参数。
例子:

<span style="font-size:14px;">#!/bin/bashecho "\$*=" $*echo "\"\$*\"=" "$*"echo "\$@=" $@echo "\"\$@\"=" "$@"echo "print each param from \$*"for var in $*do    echo "$var"doneecho "print each param from \$@"for var in $@do    echo "$var"doneecho "print each param from \"\$*\""for var in "$*"do    echo "$var"doneecho "print each param from \"\$@\""for var in "$@"do    echo "$var"done</span>
结果:
<span style="font-size:14px;">$*=  a b c d"$*"= a b c d$@=  a b c d"$@"= a b c dprint each param from $*abcdprint each param from $@abcdprint each param from "$*"a b c dprint each param from "$@"abcd</span>



三、Shell替换


1、转义符

转义字符含义\\反斜杠\a警报,响铃\b退格(删除键)\f换页(FF),将当前位置移到下页开头\n换行\r回车\t水平制表符(tab键) \v垂直制表符
例子:

#!/bin/basha=10echo -e "Value of a is $a \n"echo  "Value of a is $a \n"
结果:

Value of a is 10Value of a is 10\n

2、命令替换

例子:

#!/bin/bashDATE=`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 2009Logged in user are 1Uptime is Thu Jul  2 03:59:57 MST 200903:59:57 up 20 days, 14:03,  1 user,  load avg: 0.13, 0.07, 0.15
3、变量转换


形式说明${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/bashecho ${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 varecho ${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}"
运行结果:

<span style="font-size:14px;">Variable is not set1 - Value of var isVariable is not set2 - Value of var is Variable is not set3 - Value of var isThis is default value4 - Value of var is PrefixPrefix5 - Value of var is Prefix</span>


四、Shell 运算符



算术运算符列表运算符说明举例+加法`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。
注意:条件表达式要放在方括号之间,并且要有空格,例如 [$a==$b] 是错误的,必须写成 [ $a == $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。

布尔运算符列表运算符说明举例!非运算,表达式为 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。

字符串运算符列表运算符说明举例=检测两个字符串是否相等,相等返回 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。

文件测试运算符列表操作符说明举例-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。


五、Shell字符串


单引号字符串的限制:
单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;
单引号字串中不能出现单引号(对单引号使用转义符后也不行)。
双引号的优点:
双引号里可以有变量
双引号里可以出现转义字符

基本操作:

<span style="font-size:14px;">your_name="qinjx"greeting="hello, "$your_name" !"greeting_1="hello, ${your_name} !"echo $greeting $greeting_1string="abcd"echo ${#string} #输出 4string="alibaba is a great company"echo ${string:1:4} #输出libastring="alibaba is a great company"echo `expr index "$string" is`</span>




六、Shell 数组


bash支持一维数组不支持多维数组

定义数组

array_name=(value0 value1 value2 value3)
或者:

array_name=(value0value1value2value3)
或者:

array_name[0]=value0array_name[1]=value1array_name[2]=value2
读取数组

读取的一般格式是:

${array_name[index]}

#!/bin/shNAME[0]="Zara"NAME[1]="Qadir"NAME[2]="Mahnaz"NAME[3]="Ayan"NAME[4]="Daisy"echo "First Index: ${NAME[0]}"echo "Second Index: ${NAME[1]}"
使用@或者*可以获取数组中的所有元素

${array_name[*]}${array_name[@]}
获取数组的长度

# 取得数组元素的个数length=${#array_name[@]}# 或者length=${#array_name[*]}# 取得数组单个元素的长度lengthn=${#array_name[n]}



七、Shell printf命令


 printf命令用于格式化输出,是echo命令的增强版。

 printf不像echo那样自动换行,需要显示添加“\n”

printf 命令的语法:

printf  format-string  [arguments...]
format-string 为格式控制字符串,arguments 为参数列表。
# format-string为双引号$ printf "%d %s\n" 1 "abc"1 abc# 单引号与双引号效果一样 $ printf '%d %s\n' 1 "abc" 1 abc# 没有引号也可以输出$ printf %s abcdefabcdef# 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用$ printf %s abc defabcdef$ printf "%s\n" abc defabcdef$ printf "%s %s %s\n" a b c d e f g h i ja b cd e fg h ij# 如果没有 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 numberThe first program always prints 'Hello,0'$



八、Shell if else 语句


1) if ... fi 语句

if [ expression ]then   Statement(s) to be executed if expression is truefi
#!/bin/sha=10b=20if [ $a == $b ]then   echo "a is equal to b"fiif [ $a != $b ]then   echo "a is not equal to b"fi
2) if ...else... fi 语句
if [ expression ]then   Statement(s) to be executed if expression is trueelse   Statement(s) to be executed if expression is not truefi
3) if ...elif... fi 语句
if [ expression 1 ]then   Statement(s) to be executed if expression 1 is trueelif [ expression 2 ]then   Statement(s) to be executed if expression 2 is trueelif [ expression 3 ]then   Statement(s) to be executed if expression 3 is trueelse   Statement(s) to be executed if no expression is truefi

九、Shell case esac语句


case 值 in模式1)    command1    command2    command3    ;;模式2)    command1    command2    command3    ;;*)    command1    command2    command3    ;;esac

echo 'Input a number between 1 to 4'echo 'Your number is:\c'read aNumcase $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


十、Shell for循环


for 变量 in 列表do    command1    command2    ...    commandNdone


十一、Shell while

 

while commanddo   Statement(s) to be executed if command is truedone

十二、Shell until

until commanddo   Statement(s) to be executed until command is truedone
一直运行到条件为真为止


十三、Shell 函数

function_name () {    list of commands    [ return value ]}
或者

function function_name () {    list of commands    [ return value ]}

返回值只能是整数
#!/bin/bash# Define your function hereHello () {   echo "Url is http://see.xidian.edu.cn/cpp/shell/"}# Invoke your functionHello


#!/bin/bashfunWithReturn(){    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 commandret=$?echo "The sum of two numbers is $ret !"

十四、Shell 函数参数

#!/bin/bashfunWithParam(){    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 !"

注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数



十五、Shell 输入输出重定向

Unix 命令默认从标准输入设备(stdin)获取输入,将结果输出到标准输出设备(stdout)显示。一般情况下,标准输入设备就是键盘,标准输出设备就是终端,即显示器。

输出重定向

命令的输出不仅可以是显示器,还可以很容易的转移向到文件,这被称为输出重定向。

命令输出重定向的语法为:

$ command > file
这样,输出到显示器的内容就可以被重定向到文件。

例如,下面的命令在显示器上不会看到任何输出:
$ who > users
打开 users 文件,可以看到下面的内容:
$ cat usersoko         tty01   Sep 12 07:30ai          tty15   Sep 12 13:32ruth        tty21   Sep 12 10:10pat         tty24   Sep 12 13:07steve       tty25   Sep 12 13:03$
输出重定向会覆盖文件内容,请看下面的例子:
$ echo line 1 > users$ cat usersline 1$
如果不希望文件内容被覆盖,可以使用 >> 追加到文件末尾,例如:
$ echo line 2 >> users$ cat usersline 1line 2$
输入重定向

和输出重定向一样,Unix 命令也可以从文件获取输入,语法为:
command < file
这样,本来需要从键盘获取输入的命令会转移到文件读取内容。

注意:输出重定向是大于号(>),输入重定向是小于号(<)。

例如,计算 users 文件中的行数,可以使用下面的命令:
$ wc -l users2 users$
也可以将输入重定向到 users 文件:
$ wc -l < users2$

注意:上面两个例子的结果不同:第一个例子,会输出文件名;第二个不会,因为它仅仅知道从标准输入读取内容。
重定向深入讲解

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:
标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息。

默认情况下,command > file 将 stdout 重定向到 file,command < file 将stdin 重定向到 file。

如果希望 stderr 重定向到 file,可以这样写:
$command 2 > file
如果希望 stderr 追加到 file 文件末尾,可以这样写:
$command 2 >> file
2 表示标准错误文件(stderr)。

如果希望将 stdout 和 stderr 合并后重定向到 file,可以这样写:
$command > file 2>&1

$command >> file 2>&1
如果希望对 stdin 和 stdout 都重定向,可以这样写:
$command < file1 >file2
command 命令将 stdin 重定向到 file1,将 stdout 重定向到 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 之间的内容作为输入。

十六、Shell 文件包含


像其他语言一样,Shell 也可以包含外部脚本,将外部脚本的内容合并到当前脚本。

Shell 中包含脚本可以使用:

. filename

source filename
两种方式的效果相同,简单起见,一般使用点号(.),但是注意点号(.)和文件名中间有一空格。

例如,创建两个脚本,一个是被调用脚本 subscript.sh,内容如下:
url="http://see.xidian.edu.cn/cpp/view/2738.html"
一个是主文件 main.sh,内容如下:
#!/bin/bash. ./subscript.shecho $url

执行脚本:
$chomd +x main.sh./main.shhttp://see.xidian.edu.cn/cpp/view/2738.html$
注意:被包含脚本不需要有执行权限。

0 0
原创粉丝点击