编写Shell脚本(转)

作者: 咕咕鷄 | 来源:发表于2016-12-12 22:08 被阅读114次

转自http://c.biancheng.net/cpp/shell/

30分钟看完基本就能读懂简单的shell脚本了,如果还看不懂那就再看30分钟。(ᇂдᇂ

Shell本身是一个用C语言编写的程序,它是用户使用Unix/Linux的桥梁,用户的大部分工作都是通过Shell完成的。Shell既是一种命令语言,又是一种程序设计语言。作为命令语言,它交互式地解释和执行用户输入的命令;作为程序设计语言,它定义了各种变量和参数,并提供了许多在高级语言中才具有的控制结构,包括循环和分支。

Shell有两种执行命令的方式:
交互式(Interactive):解释执行用户的命令,用户输入一条命令,Shell就解释执行一条。
批处理(Batch):用户事先写一个Shell脚本(Script),其中有很多条命令,让Shell一次把这些命令执行完,而不必一条一条地敲命令。类似Windows的批处理(.bat)文件。

Shell变量

1.定义变量

variableName="value"

注意,等号左右两边不能有空格。规则如下:

  • 首个字符必须为字母(a-z,A-Z)。
  • 中间不能有空格,可以使用下划线(_)。
  • 不能使用标点符号。
  • 不能使用bash里的关键字(可用help命令查看保留关键字)。

2.使用变量
使用一个定义过的变量,只要在变量名前面加美元符号($)即可。

for skill in C Java Go Python
do
echo "I am good at ${skill}."
done

I am good at C.
I am good at Java.
I am good at Go.
I am good at Python.

加花括号是为了帮助解释器识别变量的边界,推荐给所有变量加上花括号,这是个好的编程习惯。

3.重新定义变量
已经定义的变量,可以被重新定义。

myUrl="http://see.xidian.edu.cn/cpp/linux/"
echo ${myUrl}
myUrl="http://see.xidian.edu.cn/cpp/shell/"
echo ${myUrl}

http://see.xidian.edu.cn/cpp/linux/
http://see.xidian.edu.cn/cpp/shell/

4.只读变量
readonly命令可以将变量定义为只读变量。

#!/bin/bash
myUrl="http://see.xidian.edu.cn/cpp/shell/"
readonly myUrl
myUrl="http://see.xidian.edu.cn/cpp/danpianji/"

报错

-bash: myUrl: readonly variable

5.删除变量

unset命令可以删除变量。

#!/bin/sh
myUrl="http://see.xidian.edu.cn/cpp/u/xitong/"
unset myUrl
echo $myUrl

Shell特殊变量

变量 含义
$0 当前脚本的文件名
$n 传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。
$# 传递给脚本或函数的参数个数。
$* 传递给脚本或函数的所有参数。
$@ 传递给脚本或函数的所有参数。被双引号(" ")包含时,与 $* 稍有不同,下面将会讲到。
$? 上个命令的退出状态,或函数的返回值。
$$ 当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。

"$*"整体输出,"$@"和$@一样。

Shell替换

#!/bin/bash
a=10
echo -e "Value of a is $a \n"

-e表示对转义字符进行替换,转义字符如下:

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

1.命令替换

`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

2.变量替换

形式 说明
${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 的值。

Shell运算符

原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 awk 和 expr,expr 最常用。
expr 是一款表达式计算工具,使用它能完成表达式的求值操作。

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

输出 Total value : 4

两点注意:
表达式和运算符之间要有空格,例如 2+2 是不对的,必须写成 2 + 2,这与我们熟悉的大多数编程语言不一样。
完整的表达式要被 \ ` ` 包含,注意这个字符不是常用的单引号,在 Esc 键下边。

1.算术运算符

算术运算符列表

运算符 说明 举例
+ 加法 `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。

2.关系运算符

关系运算符只支持数字,不支持字符串,除非字符串的值是数字。
关系运算符列表

运算符 说明 举例
-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。

3.布尔运算符

布尔运算符列表

运算符 说明 举例
! 非运算,表达式为 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。 [ -n $a ] 返回 true。
str 检测字符串是否为空,不为空返回 true。 [ $a ] 返回true。
#!/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

4.文件测试运算符

文件测试运算符列表

操作符 说明 举例
-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注释

以“#”开头的行就是注释,会被解释器忽略。

Shell字符串

1.单引号

str='this is a string'

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

2.双引号

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

双引号的优点:
双引号里可以有变量
双引号里可以出现转义字符

3.拼接字符串

your_name="qinjx"
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting $greeting_1

4.获取字符串长度

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

5.提取子字符串

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

6.查找子字符串

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

Shell数组

1.定义数组

array_name=(value0 value1 value2 value3)

2.读取数组

valuen=${array_name[2]}
${array_name[*]} #所有元素
${array_name[@]} #所有元素

3.获取数组长度

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

Shell echo命令

1.显示转义字符

echo "\"It is a test\""

输出"It is a test”

2.显示变量

name="OK"
echo "$name It is a test"

3.显示换行

echo "OK!\n"
echo "It is a test"

4.显示不换行

echo "OK!\c"
echo "It is a test"

5.显示结果重定向至文件

echo "It is a test" > myfile

6.原样输出字符串

echo '$name\"'

单引号原样输出

7.显示命令执行结果

echo `date`

Shell printf命令

# 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
abc
def
$ 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'
$

Shell ifelse语句

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

  • if ... fi 语句;
  • if ... else ... fi 语句;
  • if ... elif ... else ... fi 语句。
if [ expression ]
then 
  Statement(s) to be executed if expression is true
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
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

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

Shell for循环

for 变量 in 列表
do 
  command1 
  command2 
  ... 
  commandN
done
for loop in 1 2 3 4 5
do
  echo "The value is: $loop"
done

Shell while循环

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

Shell until循环

until command
do 
  Statement(s) to be executed until command is true
done
#!/bin/bash
a=0
until [ ! $a -lt 10 ]
do
  echo $a
  a=`expr $a + 1`
done

Shell 跳出循环

break

#!/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 命令后面还可以跟一个整数,表示跳出第几层循环。例如:

break n

表示跳出第 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

continue

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

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

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

Shell函数

Shell 函数的定义格式如下:

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

调用函数只需要给出函数名,不需要加括号。

像删除变量一样,删除函数也可以使用 unset 命令,不过要加上 .f 选项,如下所示:

$unset .f function_name

Shell函数参数

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

输出到显示器的内容就可以被重定向到文件。

command < file

本来需要从键盘获取输入的命令会转移到文件读取内容。

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

全部可用的重定向命令列表

命令 说明
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 之间的内容作为输入。

如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到/dev/null:

$ command > /dev/null

如果希望屏蔽 stdout 和 stderr,可以这样写:

$ command > /dev/null 2>&1

Shell文件包含

Shell 中包含脚本可以使用:

. filename

source filename

相关文章

  • 编写Shell脚本(转)

    转自http://c.biancheng.net/cpp/shell/ 30分钟看完基本就能读懂简单的shell脚...

  • Shell script + crontab实现Mysql定时备

    一、Shell 脚本 Shell 脚本(shell script),是一种为 shell 编写的脚本程序。 业界所...

  • 多命令处理

    编写shell脚本 执行脚本

  • shell脚本

    什么是shell脚本 Shell 脚本(shell script),是一种为 shell 编写的脚本程序。业界所说...

  • Shell脚本语法

    1. Shell脚本简介Shell 脚本(shell script),是一种为 shell 编写的脚本程序。业界所...

  • shell脚本基础

    编写脚本 编程基础 shell脚本 创建shell脚本 变量 运算 测试 配置用户的环境

  • web3js脚本编写

    转账脚本 编写转账的js脚本,保存在transactionTest.js文件中 在shell中敲如下命令 转币合约...

  • 78.shell编程

    shell编程 Shell脚本,是一种为shell编写的脚本程序。 Shell编程跟JavaScript、Pyth...

  • shell快速学习指南(二)

    Shell 脚本的编写 我们可以直接在shell提示符下编写shell脚本,比如函数、控制语句等都可以直接在she...

  • Shell 脚本入门: 编写格式和执行方式

    本文要点 Shell 脚本的编写规范 执行Shell 脚本文件的 3 种方式 与 区别 1. Shell 脚本的编...

网友评论

    本文标题:编写Shell脚本(转)

    本文链接:https://www.haomeiwen.com/subject/dpgmmttx.html