ubuntu的sh文件编程(二)

继续(一)的学习。

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

sh里没有多行注释,只能每一行加一个#号。只能像这样:

   
   
  1. #--------------------------------------------
  2. # 这是一个自动打ipa的脚本,基于webfrogs的ipa-build书写:
  3. # https://github.com/webfrogs/xcode_shell/blob/master/ipa-build
  4. # 功能自动为etao ios app打包,产出物为14个渠道的ipa包
  5. # 特色:全自动打包,不需要输入任何参数
  6. #--------------------------------------------
  7. ##### 用户配置区 开始 #####
  8. #
  9. #
  10. # 项目根目录,推荐将此脚本放在项目的根目录,这里就不用改了
  11. # 应用名,确保和Xcode里Product下的target_name.app名字一致
  12. #
  13. ##### 用户配置区 结束 #####
如果在开发过程中,遇到大段的代码需要临时注释起来,过一会儿又取消注释,怎么办呢?每一行加个#符号太费力了,可以把这一段要注释的代码用一对花括号括起来,定义成一个函数,没有地方调用这个函数,这块代码就不会执行,达到了和注释一样的效果

字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。单双引号的区别跟PHP类似。

单引号

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

双引号

   
   
  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. 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在编程方面比Windows批处理强大很多,无论是在循环、运算。

bash支持一维数组(不支持多维数组),并且没有限定数组的大小。类似与C语言,数组元素的下标由0开始编号。获取数组中的元素要利用下标,下标可以是整数或算术表达式,其值应大于或等于0。

定义数组

在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. NAME[0]="Zara"
  3. NAME[1]="Qadir"
  4. NAME[2]="Mahnaz"
  5. NAME[3]="Ayan"
  6. NAME[4]="Daisy"
  7. echo "First Index: ${NAME[0]}"
  8. echo "Second Index: ${NAME[1]}"
运行脚本,输出
$./test.sh
First Index: Zara
Second Index: Qadir
使用@ 或 * 可以获取数组中的所有元素,例如:
   
   
  1. ${array_name[*]}
  2. ${array_name[@]}
举个例子:
   
   
  1. #!/bin/sh
  2. NAME[0]="Zara"
  3. NAME[1]="Qadir"
  4. NAME[2]="Mahnaz"
  5. NAME[3]="Ayan"
  6. NAME[4]="Daisy"
  7. echo "First Method: ${NAME[*]}"
  8. 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]}
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`
结果将显示当前日期

从上面可看出,双引号可有可无,单引号主要用在原样输出中。

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命令都支持浮点格式。

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. a=10
  3. b=20
  4. if [ $a == $b ]
  5. then
  6. echo "a is equal to b"
  7. fi
  8. if [ $a != $b ]
  9. then
  10. echo "a is not equal to b"
  11. 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. a=10
  3. b=20
  4. if [ $a == $b ]
  5. then
  6. echo "a is equal to b"
  7. else
  8. echo "a is not equal to b"
  9. 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. a=10
  3. b=20
  4. if [ $a == $b ]
  5. then
  6. echo "a is equal to b"
  7. elif [ $a -gt $b ]
  8. then
  9. echo "a is greater than b"
  10. elif [ $a -lt $b ]
  11. then
  12. echo "a is less than b"
  13. else
  14. echo "None of the condition met"
  15. 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 命令用于检查某个条件是否成立,与方括号([ ])类似。

case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构。

case 语句匹配一个值或一个模式,如果匹配成功,执行相匹配的命令。case语句格式如下:

case 值 in
模式1)
    command1
    command2
    command3
    ;;
模式2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
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. option="${1}"
  3. case ${option} in
  4. -f) FILE="${2}"
  5. echo "File name is $FILE"
  6. ;;
  7. -d) DIR="${2}"
  8. echo "Dir name is $DIR"
  9. ;;
  10. *)
  11. echo "`basename ${0}`:usage: [-f file] | [-d directory]"
  12. exit 1 # Command to come out of the program with status 1
  13. ;;
  14. 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. for FILE in $HOME/.bash*
  3. do
  4. echo $FILE
  5. 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
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. a=0
  3. until [ ! $a -lt 10 ]
  4. do
  5. echo $a
  6. a=`expr $a + 1`
  7. done
运行结果:
0
1
2
3
4
5
6
7
8
9
在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,像大多数编程语言一样,Shell也使用 break 和 continue 来跳出循环。

break命令

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. for var1 in 1 2 3
  3. do
  4. for var2 in 0 5
  5. do
  6. if [ $var1 -eq 2 -a $var2 -eq 0 ]
  7. then
  8. break 2
  9. else
  10. echo "$var1 $var2"
  11. fi
  12. done
  13. 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. NUMS="1 2 3 4 5 6 7"
  3. for NUM in $NUMS
  4. do
  5. Q=`expr $NUM % 2`
  6. if [ $Q -eq 0 ]
  7. then
  8. echo "Number is an even number!!"
  9. continue
  10. fi
  11. echo "Found odd number"
  12. 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
函数可以让我们将一个复杂功能划分成若干模块,让程序结构更加清晰,代码重复利用率更高。像其他编程语言一样,Shell 也支持函数。Shell 函数必须先定义后使用。

Shell 函数的定义格式如下:
function_name () {
    list of commands
    [ return value ]
}
如果你愿意,也可以在函数名前加上关键字 function:
function function_name () {
    list of commands
    [ return value ]
}
函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。

Shell 函数返回值只能是整数,一般用来表示函数执行成功与否,0表示成功,其他值表示失败。如果 return 其他数据,比如一个字符串,往往会得到错误提示:“numeric argument required”。

如果一定要让函数返回字符串,那么可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值。

先来看一个例子:
   
   
  1. #!/bin/bash
  2. # Define your function here
  3. Hello () {
  4. echo "Url is http://see.xidian.edu.cn/cpp/shell/"
  5. }
  6. # Invoke your function
  7. Hello
运行结果:
$./test.sh
Hello World
$
调用函数只需要给出函数名,不需要加括号。

再来看一个带有return语句的函数
   
   
  1. #!/bin/bash
  2. funWithReturn(){
  3. echo "The function is to get the sum of two numbers..."
  4. echo -n "Input first number: "
  5. read aNum
  6. echo -n "Input another number: "
  7. read anotherNum
  8. echo "The two numbers are $aNum and $anotherNum !"
  9. return $(($aNum+$anotherNum))
  10. }
  11. funWithReturn
  12. # Capture value returnd by last command
  13. ret=$?
  14. 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 !
函数返回值在调用函数后通过 $? 来获得。

再来看一个函数嵌套的例子:
   
   
  1. #!/bin/bash
  2. # Calling one function from another
  3. number_one () {
  4. echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
  5. number_two
  6. }
  7. number_two () {
  8. echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
  9. }
  10. 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 选项,如下所示:
   
   
  1. $unset .f function_name
如果你希望直接从终端调用函数,可以将函数定义在主目录下的 .profile 文件,这样每次登录后,在命令提示符后面输入函数名字就可以立即调用

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...

带参数的函数示例:

   
   
  1. #!/bin/bash
  2. funWithparam(){
  3. echo "The value of the first parameter is $1 !"
  4. echo "The value of the second parameter is $2 !"
  5. echo "The value of the tenth parameter is $10 !"
  6. echo "The value of the tenth parameter is ${10} !"
  7. echo "The value of the eleventh parameter is ${11} !"
  8. echo "The amount of the parameters is $# !" # 参数个数
  9. echo "The string of the parameters is $* !" # 传递给函数的所有参数
  10. }
  11. 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)显示。一般情况下,标准输入设备就是键盘,标准输出设备就是终端,即显示器。

输出重定向

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

命令输出重定向的语法为:
   
   
  1. $ command > file
这样,输出显示器的内容就可以被重定向文件

例如,下面的命令在显示器上不会看到任何输出
   
   
  1. $ who > users
打开 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
$

输入重定向

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

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

例如,计算 users 文件中的行数,可以使用下面的命令:
$ wc -l users
2 users
$
也可以将输入重定向到 users 文件
$ wc -l < users
2
$
注意:上面两个例子的结果不同:第一个例子,会输出文件名;第二个不会,因为它仅仅知道从标准输入读取内容

重定向深入讲解

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件
认情况下,command > file 将 stdout 重定向到 file,command < file 将stdin 重定向到 file。

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

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

Here Document

Here Document 目前没有统一的翻译,这里暂译为”嵌入文档“。Here Document 是 Shell 中的一种特殊的重定向方式,它的基本的形式如下:
   
   
  1. command << delimiter
  2. document
  3. delimiter
它的作用是将两个 delimiter 之间的内容(document) 作为输入传递给 command。

注意:
  • 结尾的delimiter 一定要顶格写,前面不能有任何字符,后面也不能有任何字符,包括空格和 tab 缩进。
  • 开始的delimiter前后的空格会被忽略掉。

下面的例子,通过 wc -l 命令计算 document 的行数:
$wc -l << EOF
    This is a simple lookup program
    for good (and bad) restaurants
    in Cape Town.
EOF
3
$
也可以 将 Here Document 用在脚本中,例如:
   
   
  1. #!/bin/bash
  2. cat << EOF
  3. This is a simple lookup program
  4. for good (and bad) restaurants
  5. in Cape Town.
  6. EOF
运行结果:
This is a simple lookup program
for good (and bad) restaurants
in Cape Town.

下面的脚本通过 vi 编辑器将 document 保存到 test.txt 文件
   
   
  1. #!/bin/sh
  2. filename=test.txt
  3. vi $filename <<EndOfCommands
  4. i
  5. This file was created automatically from
  6. a shell script
  7. ^[
  8. ZZ
  9. EndOfCommands
运行脚本:
$ sh test.sh
Vim: Warning: Input is not from a terminal
$
打开 test.txt,可以看到下面的内容
$ cat test.txt
This file was created automatically from
a shell script
$

/dev/null 文件

如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到/dev/null:
   
   
  1. $ command > /dev/null
/dev/null 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。但是/dev/null 文件非常有用,将命令的输出重定向到它,会起到”禁止输出“的效果

如果希望屏蔽 stdout 和 stderr,可以这样写:
 
 
  1. $ command > /dev/null 2>&1
像其他语言一样,Shell 也可以包含外部脚本,将外部脚本的内容合并到当前脚本。

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

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

注意:被包含脚本不需要有执行权限。

扩展知识:

命令tr(translate缩写)主要用于删除文件中的控制字符,或进行字符转换。
语法:tr [–c/d/s/t] [SET1] [SET2]
SET1: 字符集1
SET2:字符集2
-c:complement,用SET2替换SET1中没有包含的字符
-d:delete,删除SET1中所有的字符,不转换
-s: squeeze-repeats,压缩SET1中重复的字符
-t: truncate-set1,将SET1用SET2转换,一般缺省为-t

1、去除重复的字符
#将连续的几个相同字符压缩为一个字符
$ echo aaacccddd | tr -s [a-z]
acd
$ echo aaacccddd | tr -s [abc]
acddd

2、删除空白行
#删除空白行就是删除换行符/n
#注意:这些空白行上只有回车符,没有空格符
$ cat test.txt
I love linux!


Hello World!

Shell is worthy to been studied

#这里用换行符的转义字符\n
#注意:此处用-s删除了多余的换行符,如果用-d,则会删除所有的换行符
$ cat test.txt | tr -s ["\n"]
I love linux!
Hello World!
Shell is worthy to been studied
#也可以用八进制符\012,\012与\n都是换行符
$ cat test.txt | tr -s "[\012]"
I love linux!
Hello World!
Shell is worthy to been studied

3、大小写相互转换
#将语句中所有的小写字母变成大写字母,其中-t可省略
$ echo "Hello World I love You" |tr [-t] [a-z] [A-Z]
HELLO WORLD I lovE YOU
#将语句中所有的大写字母变成小写字母
$ echo "Hello World I love You" |tr [A-Z] [a-z]
hello world i love you
#也可以利用字符类进行转换
#[:lower:]代表小写字母,[:upper:]代表大写字母
$ echo "Hello World I love You" |tr [:lower:] [:upper:]
HELLO WORLD I lovE YOU

4、删除指定的字符
$ cat test.txt
Monday 09:00
Tuesday 09:10
Wednesday 10:11
Thursday 11:30
Friday 08:00
Saturday 07:40
Sunday 10:00
#现在要删除处理星期之外的所有字符
#-d代表删除,[0-9]代表所有的数字,[: ]代表冒号和空格
$ cat test.txt | tr -d "[0-9][: ]"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

5、利用-c进行补集的替换
#有时候在文本中我们只知道要保留的一些字符,其他字符种类繁多,就可以使用补集的替换
$ cat test.txt
Monday 09:00
Tuesday 09:10
Wednesday 10:11
Thursday 11:30
Friday 08:00
Saturday 07:40
Sunday 10:00
#我们只需要星期,则思路就是除了字母,其他统统替换掉
#这里,-c:用换行符替换掉除了字母外的所有字符;-s:删除多余的换行符
cat test.txt|tr -cs "[a-z][A-Z]" "\n"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

收工。。。。。。。。。。。

感谢:

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

相关文章

目录前言一、创建Hadoop用户二、更新apt和安装Vim编辑器三、...
原文连接:https://www.cnblogs.com/yasmi/p/5192694.html ...
电脑重启后,打开VirtualBox,发现一直用的虚拟机莫名的消失...
参见:https://blog.csdn.net/weixin_38883338/article/deta...
Ubuntu 18.04 LTS 已切换到 Netplan 来配置网络接口。Netpla...
介绍每个 Web 服务都可以通过特定的 URL 在 Internet 上访问...