Linux_bash_shell

在屏幕上显示Hello ! how are you

21/home/pasgs_run/log/debug> mkdir test; cd test

21/home/pasgs_run/log/debug/test> vi test01-hello.sh

#!/bin/bash

#这个脚本的用途在于在屏幕上显示Hello ! how are you

#创建日期:2015

hello=Hello\ \!\ How\ are\ you\ \?

echo $hello

 

"test01-hello.sh" [New] 7L, 146C written  

                                                                                                            

21/home/pasgs_run/log/debug/test> ls

test01-hello.sh

21/home/pasgs_run/log/debug/test> sh test01-hello.sh

Hello ! How are you ?

 

并非加上.sh 加上可执行文件,还要查看其属性中是否有x属性

 

 

引用两个变量,顺便比较一下" 与' 的异同

21/home/pasgs_run/log/debug/test> vi test02-2var.sh

#!/bin/bash

#这个脚本用于引用两个变量,顺便比较一下" 与' 的异同

#Date:2015

name="V.Bird"

myname1="my name is $name"

myname2='my name is $name'

echo $name

echo $myname1

echo $myname2

 

"test02-2var.sh" [New] 10L, 200C written                                                                                                             

21/home/pasgs_run/log/debug/test> sh test02-2var.sh

V.Bird

my name is V.Bird

my name is $name

21/home/pasgs_run/log/debug/test>

 

从输出结果看,"与'最大的不同就在于能不能保存变量内容,单引号里的数据都将变成单纯的字符

 

卷标与运算符declare (定义变量)

输入2*3+5*13-32+25 并且输出 your result is ==> 要怎么写

21/home/pasgs_run/log/debug/test> vi test03-declare.sh

#!/bin/bash

#this program is used to "declare" variables

# 2015

number1=2*3+5*13-32+25

declare -i number2=2*3+5*13-32+25

echo "your result is ==> $number1"

echo "your result is ==> $number2"

 

"test03-declare.sh" [New] 8L, 197C written                                                                                                           

21/home/pasgs_run/log/debug/test> ls

test01-hello.sh  test02-2var.sh  test03-declare.sh

21/home/pasgs_run/log/debug/test> sh test03-declare.sh

your result is ==> 2*3+5*13-32+25

your result is ==> 64

21/home/pasgs_run/log/debug/test>

 

交互式脚本

将键盘输入的数据显示出来,怎么做

21/home/pasgs_run/log/debug/test> vi test04-read.sh

#!/bin/bash

#this program is used to "read" variables

# 2015

echo "please keyin your name,and press enter to start."

read name

echo "this is your keyin data ==> $name"

 

"test04-read.sh" [New] 7L, 175C written                                                                                                              

21/home/pasgs_run/log/debug/test> ls

test01-hello.sh  test02-2var.sh  test03-declare.sh  test04-read.sh

21/home/pasgs_run/log/debug/test> sh test04-read.sh

please keyin your name,and press enter to start.

 Tsai

this is your keyin data ==>  Tsai

21/home/pasgs_run/log/debug/test>

 

 

定义脚本的参数代号

21/home/pasgs_run/log/debug/test> vi test05-0123

#!/bin/bash

#this program will define what is the parameters

# 2015

echo "this script's name => $0"

echo "parameters $1 $2 $3"

 

"test05-0123" [New] 7L, 134C written                                                                                                                 

21/home/pasgs_run/log/debug/test> ls

test01-hello.sh  test02-2var.sh  test03-declare.sh  test04-read.sh  test05-0123

21/home/pasgs_run/log/debug/test> sh test05-0123

this script's name => test05-0123

parameters   

21/home/pasgs_run/log/debug/test>

 

 

逻辑判断式

条件判断 ifthenfi

最常用的是 if …then…else  if…then…end  if

语法:

If  [条件判断一] &&(||)[条件判断二] ; then  <==if 是起始,后面可以接若干个判断式,使用&& 或 ||执行判断

elif  {条件判断试三}  &&  (||)  [条件判断四] ;  then  <==第二段判断,如果第一段不符合要求就转到此搜寻条件,执行第二段程序

else    <==当前两段都不符合时,就执行这段内容

fi      <==结束 if then的条件判断

 

注意:

  1. 在[]中,只能有一个判断式
  2. 在[]与[]间,可以使用&&或||结合判断式
  3. 每一个独立的组件之间需要用空格键隔开

例子:

echo "press y to continue"

read yn

if [ "$yn" = "y" ]; then

      echo "script is running..."

else

     echo "stop!"

fi

 

当输入y时,程序继续执行,若不是y 则程序停止执行,如果我输入为y 程序还是停止了 怎么办?这个时候就需要用到||

 

echo "press y to continue"

read yn

if [ "$yn" = "y" ] || [ "$yn" = "Y" ] ; then

      echo "script is running..."

else

    echo "stop!"

fi

 

如果加上前面提到的参数

if [ "$1" = "hello" ]; then

      echo "hello! how are you ?"

elif [ "$1" = "" ];then

      echo "you must input parameters"

else

     echo "the only accept parameter is hello"

fi

 

"test01-holle.sh" 7L, 181C written                                                                                                                   

21/home/pasgs_run/log/debug/test> ls

test01-holle.sh

21/home/pasgs_run/log/debug/test> sh test01-holle.sh

you must input parameters

21/home/pasgs_run/log/debug/test> sh test01-holle.sh hello

hello! how are you ?

21/home/pasgs_run/log/debug/test> sh test01-holle.sh djdkf

the only accept parameter is hello

21/home/pasgs_run/log/debug/test>

 

如果要来检测你主机上的终端口是否开启,可以使用下面的范例

#!/bin/bash  <==声明使用的shell类型

echo "now, the services of your linux system will be detect!"

echo "the www,ftp,ssh,and sendmail + pop3 will be detect!"

echo " "

#2.www

www='netstat -an|grep listen|grep :80'  <==这个就是变量并且使用了管线命令

if [ "$www" != "" ]; then      <==开始条件判断

    echo "www is running"

else

    echo "www is not running"

fi

#3.ftp

ftp='netstat -an|grep listen|grep :21'

if [ "$ftp" != "" ]; then

   echo "ftp is running"

else

   echo "ftp is not running"

fi

#4.ssh

ssh='netstat -an|grep listen|grep :22'

if [ "$ftp" != "" ];then

   echo "ssh is running"

fi

#5. sendmail + pop3

smtp='netstat -an|grep listen|grep :25'

pop3='netstat -an|grep listen|grep :110'

if [ "$smtp" != "" ] && [ "$pop3" != "" ];then  <==有两个条件以上时就使用&&等进行分隔

   echo "sendmail is ok!"

elif [ "$smtp" != "" ] && [ "$pop3" != "" ]; then

   echo "sendmail have some problem of your pop3"

elif [ "$smtp" = "" ] && [ " $pop3" != ""]; then

   echo "sendmail have some problem of your smtp"

else

   echo "sendmail is not running"

fi

 

"port.sh" 36L, 940C written

21/home/pasgs_run/log/debug/test> ls

port.sh  test01-holle.sh

21/home/pasgs_run/log/debug/test> sh port.sh

now, the services of your linux system will be detect!

the www,ftp,ssh,and sendmail + pop3 will be detect!

 

www is running

ftp is running

ssh is running

sendmail is ok!

21/home/pasgs_run/log/debug/test>

这样就可以解析主机上的数据了

 

Caseesac

上面的if then fi是以程序自行判断,那么如果我已经规划好几个项,只要选择执行的种类方式,就可以正确执行,要怎么做?最简单的例子就是我们常用到的/etc/rc.d/init.d/中的脚本,例如重新启动xinetd是使用:/etc/rc.d/init.d
/xinetd restart

注意,这是restart项,然后脚本会自动搜寻restart项去执行,这就是case…esac的使用模式。用法如下

Case   种类方式(string)  in  <==开始阶段,种类方式可分成两种类型,通常使用$1这种直接输入类型

       种类方式一

          程序执行段

      ;;      <==种类方式一的结束符号

      种类方式二

          程序执行段

      ;;     <==结束符号

   Echo “usage: {种类方式一|种类方式二} “

   Exit  1

Esac      <==结束处

 

例子:

Echo “this program will print your selection!”

Case $1 in

One)

   Echo “your choice is one”

;;

Two)

   Echo “your choice is two”

;;

Three)

   Echo “your choice is three”

;;

*)

  Echo “usage {one|two|three}”

  Exit 1

Esac

 

 

 

 

交互式的case语句又是怎样的?我们对上面的例子做个修改。

Echo “press your select one,two,three”

Read number

Case $number in

 One)

     Echo “your choice is one”

 ;;

Two)

Echo “your choice is two”

 ;;
*)

Echo “usage {one|two|three}”

Exit 1

Esac

 

 

 

 

 

 

 

循环

最简单循环语句如下:

For ((条件1;条件2;条件3))

For  variable in  variable1  variable2 …

While [condition1] &&{||} [condition2] …..

Until [condition] &&{||}[condition2]…

For 是已经知道要运行几次,

Until  直到条件符合的时候才退出程序

While 当条件符合时 就继续做

假如我们要计算1+2+…100 用脚本如何写?很多方式,我们来谈谈do…done

 

Declare   -i   s  #    <==变量声明

For ((i=1;i<=100;i=i+1))

Do

   S=s+i

Done

Echo “the count is ==>$s”

 

 

注意 for((条件1;条件2;条件3))是必要的

条件1 是初始值

条件2终止值

条件3是步阶,也就是说i每次加1

 

那么使用while或until要怎么执行?

1.使用while

Declare  -i  i

Declare -i  s

While  [ “$i” != ”101” ]

Do

     S=s+i

     I=i+1

Done

Echo “the count is ==>$s”

 

 

2.使用until

Declare -i  i

Declare -i s

Until[“$1”=”101”]

Do

   S=s+i

   I=i+1

Done

Echo “the count is==>$s”

 

下面的例子是另外一种循环方式,可以用来判断非数字类型

LIST=”tomy jony mary geoge”

For I in $LIST

Do

Echo $i

Done

 

这种格式是以空格键分开i变量的各选择项,也就是说上面的$LIST变量中,以空格键分隔共可以分离出4个项,所以,使用do…done就可以分别输出这4个项,那么,有没有办法利用这个特性将你的linux主机账号显示出来?我们利用cut跟sort及/etc/passwd文件来完成这个脚本,如下

Account=’cut –d “:” –fl  /etc/passwd|sort’  # cut裁剪 -d指定域分隔符,-f 指定要剪出哪几个域  sort排序

Echo “the following is your linux server’s account”

For I in $account

Do

   Echo $i

Done

 

接下来我们以交互式实现循环功能,即当我们输入Y或y时,程序就结算,可以这样子做

echo "pless y/Y to stop"

until [ "$yn" = "y" ] || [ "$yn" = "Y" ]

do

   read yn

done

  echo "stop here"

 

判别某个文件是否存在

#!/bin/bash

if [ ! -e done ]; then

   touch done

   echo "just make a file done"

   exit 1

elif [ -e done ] && [ -f done ]; then

   rm done

   mkdir doo

   echo "remove file==>doo"

   echo "and make directory daa"

exit 1

elif [ -e done ] && [ -d done ]; then

   rm -rf done

   echo "remove directory ==>done"

exit 1

else

echo "does here have anything?"

fi

 

21/home/pasgs_run/log/debug/test> ls

case  declare  done  echo  else  for  if  list  read  touch  until  while  yu  yy

21/home/pasgs_run/log/debug/test> sh touch

remove file==>doo

and make directory daa

21/home/pasgs_run/log/debug/test> ls

case  declare  doo  echo  else  for  if  list  read  touch  until  while  yu  yy

 

如何调试脚本

Sh  [-nvx]   scripts

-n :不执行脚本,查询脚本内的语法,若有错误则列出

-v : 在执行脚本之前,先将脚本的内容显示在屏幕上

-x : 将用到的脚本内容显示在屏幕上,与-v稍微不同

 

 

只读变量readonly

使用readonly命令可以将变量定义为只读变量

#!/bin/bash

Myurl=http://see/shell/

Readonly myurl

Myurl=http://see/danpianji/

运行脚本结果:this variable is read only

使用unset命令可以删除变量

语法Unset variable_name

变量被删除后不能再次使用,unset命令不能删除只读变量

Myurl=http://see/xitong/

Unset myurl

Echo $myurl

上面的脚本没有任何输出

变量类型

运行shell时,会同时存在三种变量:

1) 局部变量

局部变量在脚本或命令中定义,仅在当前shell实例中有效,其他shell启动的程序不能访问局部变量。

2) 环境变量

所有的程序,包括shell启动的程序,都能访问环境变量,有些程序需要环境变量来保证其正常运行。必要的时候shell脚本也可以定义环境变量。

3) shell变量

shell变量是由shell程序设置的特殊变量。shell变量中有一部分是环境变量,有一部分是局部变量,这些变量保证了shell的正常运行

特殊变量

特殊变量列表

变量

含义

$0

当前脚本的文件名

$n

传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。

$#

传递给脚本或函数的参数个数。

$*

传递给脚本或函数的所有参数。

$@

传递给脚本或函数的所有参数。被双引号(" ")包含时,与 $* 稍有不同,下面将会讲到。

$?

上个命令的退出状态,或函数的返回值。

$$

当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。

命令行参数

运行脚本时传递给脚本的参数称为命令行参数。命令行参数用 $n 表示,例如,$1 表示第一个参数,$2 表示第二个参数,依次类推。

请看下面的脚本:

  1. #!/bin/bash
  2.  
  3. echo "File Name: $0"
  4. echo "First Parameter : $1"
  5. echo "First Parameter : $2"
  6. echo "Quoted Values: $@"
  7. echo "Quoted Values: $*"
  8. 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

$* 和 $@ 的区别

$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号(" ")包含时,都以"$1" "$2" … "$n" 的形式输出所有参数。

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

下面的例子可以清楚的看到 $* 和 $@ 的区别:

  1. #!/bin/bash
  2. echo "\$*=" $*
  3. echo "\"\$*\"=" "$*"
  4.  
  5. echo "\$@=" $@
  6. echo "\"\$@\"=" "$@"
  7.  
  8. echo "print each param from \$*"
  9. for var in $*
  10. do
  11.     echo "$var"
  12. done
  13.  
  14. echo "print each param from \$@"
  15. for var in $@
  16. do
  17.     echo "$var"
  18. done
  19.  
  20. echo "print each param from \"\$*\""
  21. for var in "$*"
  22. do
  23.     echo "$var"
  24. done
  25.  
  26. echo "print each param from \"\$@\""
  27. for var in "$@"
  28. do
  29.     echo "$var"
  30. done

执行 ./test.sh "a" "b" "c" "d",看到下面的结果:

$*=  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

退出状态

$? 可以获取上一个命令的退出状态。所谓退出状态,就是上一个命令执行后的返回结果。

退出状态是一个数字,一般情况下,大部分命令执行成功会返回 0,失败返回 1。

不过,也有一些命令返回其他值,表示不同类型的错误。

下面例子中,命令成功执行:

$./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

$


$? 也可以表示函数的返回值,后续将会讲解。

 

Shell替换,变量替换,命令替换,转义字符

举个例子:

  1. #!/bin/bash
  2.  
  3. a=10
  4. echo -e "Value of a is $a \n"

运行结果:

Value of a is 10

这里 -e 表示对转义字符进行替换。如果不使用 -e 选项,将会原样输出:

Value of a is 10\n


下面的转义字符都可以用在 echo 中:

转义字符

含义

\\

反斜杠

\a

警报,响铃

\b

退格(删除键)

\f

换页(FF),将当前位置移到下页开头

\n

换行

\r

回车

\t

水平制表符(tab键) 

\v

垂直制表符

命令替换

命令替换是指Shell可以先执行命令,将输出结果暂时保存,在适当的地方输出。

命令替换的语法:

  1. `command`

注意是反引号,不是单引号,这个键位于 Esc 键下方。

下面的例子中,将命令执行结果保存在变量中:

  1. #!/bin/bash
  2.  
  3. DATE=`date`
  4. echo "Date is $DATE"
  5.  
  6. USERS=`who | wc -l`
  7. echo "Logged in user are $USERS"
  8.  
  9. UP=`date ; uptime`
  10. 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}"

运行结果:

  1. Variable is not set
  2. 1 - Value of var is
  3. Variable is not set
  4. 2 - Value of var is Variable is not set
  5.  
  6. 3 - Value of var is
  7. This is default value
  8. 4 - Value of var is Prefix
  9. Prefix
  10. 5 - Value of var is Prefix

 

Shell运算符

expr 是一款表达式计算工具,使用它能完成表达式的求值操作。

例如,两个数相加:

  1. #!/bin/bash
  2.  
  3. val=`expr 2 + 2`
  4. echo "Total value : $val"

运行脚本输出:

Total value : 4

两点注意:

  • 表达式和运算符之间要有空格,例如 2+2 是不对的,必须写成 2 + 2,这与我们熟悉的大多数编程语言不一样。

完整的表达式要被 ` ` 包含,注意这个字符不是常用的单引号,在 Esc 键下边

 

算术运算符

先来看一个使用算术运算符的例子:

  1. #!/bin/sh
  2.  
  3. a=10
  4. b=20
  5. val=`expr $a + $b`
  6. echo "a + b : $val"
  7.  
  8. val=`expr $a - $b`
  9. echo "a - b : $val"
  10.  
  11. val=`expr $a \* $b`
  12. echo "a * b : $val"
  13.  
  14. val=`expr $b / $a`
  15. echo "b / a : $val"
  16.  
  17. val=`expr $b % $a`
  18. echo "b % a : $val"
  19.  
  20. if [ $a == $b ]
  21. then
  22.    echo "a is equal to b"
  23. fi
  24.  
  25. if [ $a != $b ]
  26. then
  27.    echo "a is not equal to b"
  28. fi

运行结果:

a + b : 30

a - b : -10

a * b : 200

b / a : 2

b % a : 0

a is not equal to b

注意:

  • 乘号(*)前边必须加反斜杠(\)才能实现乘法运算;
  • if...then...fi 是条件语句,后续将会讲解。

关系运算符列表

说明

举例

 

-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注释

sh里没有多行注释,只能每一行加一个#号

如果在开发过程中,遇到大段的代码需要临时注释起来,过一会儿又取消注释,怎么办呢?每一行加个#符号太费力了,可以把这一段要注释的代码用一对花括号括起来,定义成一个函数,没有地方调用这个函数,这块代码就不会执行,达到了和注释一样的效果。

 

 

Shell字符串

单引号字符串的限制:

  • 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;
  • 单引号字串中不能出现单引号(对单引号使用转义符后也不行)。

双引号

  1. your_name='qinjx'
  2. str="Hello, I know your are \"$your_name\"! \n"

双引号的优点:

  • 双引号里可以有变量
  • 双引号里可以出现转义字符

拼接字符串

  1. your_name="qinjx"
  2. greeting="hello, "$your_name" !"
  3. greeting_1="hello, ${your_name} !"
  4.  
  5. echo $greeting $greeting_1

获取字符串长度

  1. string="abcd"
  2. echo ${#string} #输出 4

提取子字符串

  1. string="alibaba is a great company"
  2. echo ${string:1:4} #输出liba

查找子字符串

  1. string="alibaba is a great company"
  2. echo `expr index "$string" is`

 

 

shell 数组

在Shell中,用括号来表示数组,数组元素用“空格”符号分割开。定义数组的一般形式为:
    array_name=(value1 ... valuen)
例如:

  1. array_name=(value0 value1 value2 value3)

或者

  1. array_name=(
  2. value0
  3. value1
  4. value2
  5. value3
  6. )


还可以单独定义数组的各个分量:

  1. array_name[0]=value0
  2. array_name[1]=value1
  3. array_name[2]=value2

可以不使用连续的下标,而且下标的范围没有限制。

读取数组

读取数组元素值的一般格式是:
    ${array_name[index]}
例如:

  1. valuen=${array_name[2]}

举个例子:

  1. #!/bin/sh
  2.  
  3. NAME[0]="Zara"
  4. NAME[1]="Qadir"
  5. NAME[2]="Mahnaz"
  6. NAME[3]="Ayan"
  7. NAME[4]="Daisy"
  8. echo "First Index: ${NAME[0]}"
  9. echo "Second Index: ${NAME[1]}"

运行脚本,输出:

$./test.sh

First Index: Zara

Second Index: Qadir

使用@ 或 * 可以获取数组中的所有元素,例如:

  1. ${array_name[*]}
  2. ${array_name[@]}

举个例子:

  1. #!/bin/sh
  2.  
  3. NAME[0]="Zara"
  4. NAME[1]="Qadir"
  5. NAME[2]="Mahnaz"
  6. NAME[3]="Ayan"
  7. NAME[4]="Daisy"
  8. echo "First Method: ${NAME[*]}"
  9. echo "Second Method: ${NAME[@]}"

运行脚本,输出:

$./test.sh

First Method: Zara Qadir Mahnaz Ayan Daisy

Second Method: Zara Qadir Mahnaz Ayan Daisy

获取数组的长度

获取数组长度的方法与获取字符串长度的方法相同,例如:

  1. # 取得数组元素的个数
  2. length=${#array_name[@]}
  3. # 或者
  4. length=${#array_name[*]}
  5. # 取得数组单个元素的长度
  6. lengthn=${#array_name[n]}

shell echo 命令

echo是Shell的一个内部指令,用于在屏幕上打印出指定的字符串。命令格式:

  1. echo arg

您可以使用echo实现更复杂的输出格式控制。

显示转义字符

  1. echo "\"It is a test\""

结果将是:
"It is a test"

双引号也可以省略。

显示变量

  1. name="OK"
  2. echo "$name It is a test"

结果将是:
OK It is a test

同样双引号也可以省略。

如果变量与其它字符相连的话,需要使用大括号({ }):

  1. mouth=8
  2. echo "${mouth}-1-2009"

结果将是:
8-1-2009

显示换行

  1. echo "OK!\n"
  2. echo "It is a test"

输出:
OK!
It is a test

显示不换行

  1. echo "OK!\c"
  2. echo "It is a test"

输出:
OK!It si a test

显示结果重定向至文件

  1. echo "It is a test" > myfile

原样输出字符串

若需要原样输出字符串(不进行转义),请使用单引号。例如:

  1. echo '$name\"'

显示命令执行结果

  1. echo `date`

结果将显示当前日期

 

Shell printf 格式化输出语句

printf 命令用于格式化输出, 是echo命令的增强版。它是C语言printf()库函数的一个有限的变形,并且在语法上有些不同。

注意:printf 由 POSIX 标准所定义,移植性要比 echo 好。

如同 echo 命令,printf 命令也可以输出简单的字符串:

  1. $printf "Hello, Shell\n"
  2. Hello, Shell
  3. $

printf 不像 echo 那样会自动换行,必须显式添加换行符(\n)。

printf 命令的语法:

printf  format-string  [arguments...]

format-string 为格式控制字符串,arguments 为参数列表。

printf()在C语言入门教程中已经讲到,功能和用法与 printf 命令类似,请查看:C语言格式输出函数printf()详解

这里仅说明与C语言printf()函数的不同:

  • printf 命令不用加括号
  • format-string 可以没有引号,但最好加上,单引号双引号均可。
  • 参数多于格式控制符(%)时,format-string 可以重用,可以将所有参数都转换。
  • arguments 使用空格分隔,不用逗号。


请看下面的例子:

  1. # format-string为双引号
  2. $ printf "%d %s\n" 1 "abc"
  3. 1 abc
  4. # 单引号与双引号效果一样
  5. $ printf '%d %s\n' 1 "abc"
  6. 1 abc
  7. # 没有引号也可以输出
  8. $ printf %s abcdef
  9. abcdef
  10. # 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用
  11. $ printf %s abc def
  12. abcdef
  13. $ printf "%s\n" abc def
  14. abc
  15. def
  16. $ printf "%s %s %s\n" a b c d e f g h i j
  17. a b c
  18. d e f
  19. g h i
  20. j
  21. # 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替
  22. $ printf "%s and %d \n"
  23. and 0
  24. # 如果以 %d 的格式来显示字符串,那么会有警告,提示无效的数字,此时默认置为 0
  25. $ printf "The first program always prints'%s,%d\n'" Hello Shell
  26. -bash: printf: Shell: invalid number
  27. The first program always prints 'Hello,0'
  28. $


注意,根据POSIX标准,浮点格式%e、%E、%f、%g与%G是“不需要被支持”。这是因为awk支持浮点预算,且有它自己的printf语句。这样 Shell程序中需要将浮点数值进行格式化的打印时,可使用小型的awk程序实现。然而,内建于bash、ksh93和zsh中的printf命令都支持 浮点格式。

 

Shell if else 语句

if 语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell 有三种 if ... else 语句:

  • if ... fi 语句;
  • if ... else ... fi 语句;
  • if ... elif ... else ... fi 语句。

1) if ... else 语句

if ... else 语句的语法:

if [ expression ]

then

   Statement(s) to be executed if expression is true

fi

如果 expression 返回 true,then 后边的语句将会被执行;如果返回 false,不会执行任何语句。

最后必须以 fi 来结尾闭合 if,fi 就是 if 倒过来拼写,后面也会遇见。

注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误。

举个例子:

  1. #!/bin/sh
  2.  
  3. a=10
  4. b=20
  5.  
  6. if [ $a == $b ]
  7. then
  8.    echo "a is equal to b"
  9. fi
  10.  
  11. if [ $a != $b ]
  12. then
  13.    echo "a is not equal to b"
  14. fi

运行结果:

a is not equal to b

2) if ... else ... fi 语句

if ... else ... fi 语句的语法:

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 后边的语句。

举个例子:

  1. #!/bin/sh
  2.  
  3. a=10
  4. b=20
  5.  
  6. if [ $a == $b ]
  7. then
  8.    echo "a is equal to b"
  9. else
  10.    echo "a is not equal to b"
  11. fi

执行结果:

a is not equal to b

3) if ... elif ... fi 语句

if ... elif ... fi 语句可以对多个条件进行判断,语法为:

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,那么不执行任何语句。

举个例子:

  1. #!/bin/sh
  2.  
  3. a=10
  4. b=20
  5.  
  6. if [ $a == $b ]
  7. then
  8.    echo "a is equal to b"
  9. elif [ $a -gt $b ]
  10. then
  11.    echo "a is greater than b"
  12. elif [ $a -lt $b ]
  13. then
  14.    echo "a is less than b"
  15. else
  16.    echo "None of the condition met"
  17. fi

运行结果:

a is less than b


if ... else 语句也可以写成一行,以命令的方式来运行,像这样:

  1. if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;


if ... else 语句也经常与 test 命令结合使用,如下所示:

  1. num1=$[2*3]
  2. num2=$[1+5]
  3. if test $[num1] -eq $[num2]
  4. then
  5.     echo 'The two numbers are equal!'
  6. else
  7.     echo 'The two numbers are not equal!'
  8. fi

输出:

The two numbers are equal!

test 命令用于检查某个条件是否成立,与方括号([ ])类似。

 

Shell case esac 语句

case工作方式如上所示。取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。

取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。

下面的脚本提示输入1到4,与每一种模式进行匹配:

  1. echo 'Input a number between 1 to 4'
  2. echo 'Your number is:\c'
  3. read aNum
  4. case $aNum in
  5.     1)  echo 'You select 1'
  6.     ;;
  7.     2)  echo 'You select 2'
  8.     ;;
  9.     3)  echo 'You select 3'
  10.     ;;
  11.     4)  echo 'You select 4'
  12.     ;;
  13.     *)  echo 'You do not select a number between 1 to 4'
  14.     ;;
  15. esac

输入不同的内容,会有不同的结果,例如:

Input a number between 1 to 4

Your number is:3

You select 3


再举一个例子:

  1. #!/bin/bash
  2.  
  3. option="${1}"
  4. case ${option} in
  5.    -f) FILE="${2}"
  6.       echo "File name is $FILE"
  7.       ;;
  8.    -d) DIR="${2}"
  9.       echo "Dir name is $DIR"
  10.       ;;
  11.    *)
  12.       echo "`basename ${0}`:usage: [-f file] | [-d directory]"
  13.       exit 1 # Command to come out of the program with status 1
  14.       ;;
  15. 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

$

 

Shell for 循环

for循环一般格式为:

for 变量 in 列表

do

    command1

    command2

    ...

    commandN

done

列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。

in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

例如,顺序输出当前列表中的数字:

  1. for loop in 1 2 3 4 5
  2. do
  3.     echo "The value is: $loop"
  4. done

运行结果:

The value is: 1

The value is: 2

The value is: 3

The value is: 4

The value is: 5

顺序输出字符串中的字符:

  1. for str in 'This is a string'
  2. do
  3.     echo $str
  4. done

运行结果:

This is a string


显示主目录下以 .bash 开头的文件:

  1. #!/bin/bash
  2.  
  3. for FILE in $HOME/.bash*
  4. do
  5.    echo $FILE
  6. done

运行结果:

/root/.bash_history

/root/.bash_logout

/root/.bash_profile

/root/.bashrc

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:

while command

do

   Statement(s) to be executed if command is true

done

命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。

以下是一个基本的while循环,测试条件是:如果COUNTER小于5,那么返回 true。COUNTER从0开始,每次循环处理时,COUNTER加1。运行上述脚本,返回数字1到5,然后终止。

  1. COUNTER=0
  2. while [ $COUNTER -lt 5 ]
  3. do
  4.     COUNTER='expr $COUNTER+1'
  5.     echo $COUNTER
  6. done

运行脚本,输出:

1

2

3

4

5


while循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量FILM,按<Ctrl-D>结束循环。

  1. echo 'type <CTRL-D> to terminate'
  2. echo -n 'enter your most liked film: '
  3. while read FILM
  4. do
  5.     echo "Yeah! great film the $FILM"
  6. done

运行脚本,输出类似下面:

type <CTRL-D> to terminate

enter your most liked film: Sound of Music

Yeah! great film the Sound of Music

 

 

 

 

Shell until循环

until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。

until 循环格式为:

until command

do

   Statement(s) to be executed until command is true

done

command 一般为条件表达式,如果返回值为 false,则继续执行循环体内的语句,否则跳出循环。

例如,使用 until 命令输出 0 ~ 9 的数字:

  1. #!/bin/bash
  2.  
  3. a=0
  4.  
  5. until [ ! $a -lt 10 ]
  6. do
  7.    echo $a
  8.    a=`expr $a + 1`
  9. done

运行结果:

0

1

2

3

4

5

6

7

8

9

 

Shell break和continue命令

break命令允许跳出所有循环(终止执行后面的所有循环)。

下面的例子中,脚本进入死循环直至用户输入数字大于5。要跳出这个循环,返回到shell提示符下,就要使用break命令。

  1. #!/bin/bash
  2. while :
  3. do
  4.     echo -n "Input a number between 1 to 5: "
  5.     read aNum
  6.     case $aNum in
  7.         1|2|3|4|5) echo "Your number is $aNum!"
  8.         ;;
  9.         *) echo "You do not select a number between 1 to 5, game is over!"
  10.             break
  11.         ;;
  12.     esac
  13. done

在嵌套循环中,break 命令后面还可以跟一个整数,表示跳出第几层循环。例如:

  1. break n

表示跳出第 n 层循环。

下面是一个嵌套循环的例子,如果 var1 等于 2,并且 var2 等于 0,就跳出循环:

  1. #!/bin/bash
  2.  
  3. for var1 in 1 2 3
  4. do
  5.    for var2 in 0 5
  6.    do
  7.       if [ $var1 -eq 2 -a $var2 -eq 0 ]
  8.       then
  9.          break 2
  10.       else
  11.          echo "$var1 $var2"
  12.       fi
  13.    done
  14. done

如上,break 2 表示直接跳出外层循环。运行结果:

1 0

1 5

continue命令

continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。

对上面的例子进行修改:

  1. #!/bin/bash
  2. while :
  3. do
  4.     echo -n "Input a number between 1 to 5: "
  5.     read aNum
  6.     case $aNum in
  7.         1|2|3|4|5) echo "Your number is $aNum!"
  8.         ;;
  9.         *) echo "You do not select a number between 1 to 5!"
  10.             continue
  11.             echo "Game is over!"
  12.         ;;
  13.     esac
  14. done

运行代码发现,当输入大于5的数字时,该例中的循环不会结束,语句

  1. echo "Game is over!"

永远不会被执行。

同样,continue 后面也可以跟一个数字,表示跳出第几层循环。

再看一个 continue 的例子:

复制纯文本新窗口

  1. #!/bin/bash
  2.  
  3. NUMS="1 2 3 4 5 6 7"
  4.  
  5. for NUM in $NUMS
  6. do
  7.    Q=`expr $NUM % 2`
  8.    if [ $Q -eq 0 ]
  9.    then
  10.       echo "Number is an even number!!"
  11.       continue
  12.    fi
  13.    echo "Found odd number"
  14. 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

 

背景工作管理

Find / -name testing &  --将该程序丢到背景中执行

fg将该程序拉回屏幕前执行

如果你正在使用VI命令 而又不想保存退出想先执行其他命令 ,可以按CTRL+z 使其状态为stop状态,并且会退出vi命令,如果想回到vi使用jobs 配合bg或fg   

21/home/pasgs_run/log/debug/test> jobs

[1]+  Stopped                 vi case

[2]-  Stopped                 vi yu

21/home/pasgs_run/log/debug/test> fg %2

可以使用kill杀掉背景中的工作,kill -9 %1

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值