Shell编程基础

本文做者:Leal

受权许可:php

编辑人员:FireHare, Dbzhang800html

咱们可使用任意一种文字编辑器,好比nedit、kedit、emacs、vi等来编写shell脚本,它必须以以下行开始(必须放在文件的第一行): 程序员

# !/bin/sh

...

符号#!用来告诉系统执行该脚本的程序,本例使用/bin/sh。编辑结束并保存后,若是要执行该脚本,必须先使其可执行: web

chmod +x filename

此后在该脚本所在目录下,输入 ./filename 便可执行该脚本。 算法

 

目录

[隐藏]

[编辑] 变量赋值和引用

Shell编程中,使用变量无需事先声明,同时变量名的命名须遵循以下规则: shell

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

须要给变量赋值时,能够这么写: express

变量名=值

要取用一个变量的值,只需在变量名前面加一个$ ( ATTENTION: Don't keep blank between the variable with the equal operator '=' ) 编程

#!/bin/sh
# 对变量赋值:
a="hello world"  #等号两边均不能有空格存在
# 打印变量a的值:
echo "A is:" $a

挑个本身喜欢的编辑器,输入上述内容,并保存为文件first,而后执行 chmod +x first 使其可执行,最后输入 ./first 执行该脚本。其输出结果以下:  ubuntu

A is: hello world

有时候变量名可能会和其它文字混淆,好比: vim

num=2
echo "this is the $numnd"

上述脚本并不会输出"this is the 2nd"而是"this is the ";这是因为shell会去搜索变量numnd的值,而实际上这个变量此时并无值。这时,咱们能够用花括号来告诉shell要打印的是num变量:

num=2
echo "this is the ${num}nd"

其输出结果为:this is the 2nd

Shell脚本中有许多变量是系统自动设定的,咱们将在用到这些变量时再做说明。除了只在脚本内有效的普通shell变量外,还有环境变量,即那些由export关键字处理过的变量。本文不讨论环境变量,由于它们通常只在登陆脚本中用到。

[编辑] Shell里的流程控制

[编辑] if 语句

"if"表达式若是条件为真,则执行then后的部分:

if ....; then
  ....
elif ....; then
  ....
else
  ....
fi

大多数状况下,可使用测试命令来对条件进行测试,好比能够比较字符串、判断文件是否存在及是否可读等等……一般用" [ ] "来表示条件测试,注意这里的空格很重要,要确保方括号先后的空格。

[ -f "somefile" ] :判断是不是一个文件
[ -x "/bin/ls" ] :判断/bin/ls是否存在并有可执行权限
[ -n "$var" ] :判断$var变量是否有值
[ "$a" = "$b" ] :判断$a和$b是否相等

执行man test能够查看全部测试表达式能够比较和判断的类型。下面是一个简单的if语句:

#!/bin/sh

if [ ${SHELL} = "/bin/bash" ]; then
   echo "your login shell is the bash (bourne again shell)"
else
   echo "your login shell is not bash but ${SHELL}"
fi

变量$SHELL包含有登陆shell的名称,咱们拿它和/bin/bash进行比较以判断当前使用的shell是否为bash。

[编辑] && 和|| 操做符

熟悉C语言的朋友可能会喜欢下面的表达式:

[ -f "/etc/shadow" ] && echo "This computer uses shadow passwords"

这里的 && 就是一个快捷操做符,若是左边的表达式为真则执行右边的语句,你也能够把它看做逻辑运算里的与操做。上述脚本表示若是/etc/shadow文件存在,则 打印”This computer uses shadow passwords”。一样shell编程中还能够用或操做(||),例如:

#!/bin/sh

mailfolder=/var/spool/mail/james
[ -r "$mailfolder" ] || { echo "Can not read $mailfolder" ; exit 1; }
echo "$mailfolder has mail from:"
grep "^From " $mailfolder

该脚本首先判断mailfolder是否可读,若是可读则打印该文件中的"From" 一行。若是不可读则或操做生效,打印错误信息后脚本退出。须要注意的是,这里咱们必须使用以下两个命令:

-打印错误信息
-退出程序

咱们使用花括号以匿名函数的形式将两个命令放到一块儿做为一个命令使用;普通函数稍后再做说明。即便不用与和或操做符,咱们也能够用if表达式完成任何事情,可是使用与或操做符会更便利不少 。

[编辑] case 语句

case表达式能够用来匹配一个给定的字符串,而不是数字(可别和C语言里的switch...case混淆)。

case ... in
   ...) do something here ;;
esac

让咱们看一个例子,file命令能够辨别出一个给定文件的文件类型,如:file lf.gz,其输出结果为:

lf.gz: gzip compressed data, deflated, original filename,
last modified: Mon Aug 27 23:09:18 2001, os: Unix

咱们利用这点写了一个名为smartzip的脚本,该脚本能够自动解压bzip2, gzip和zip 类型的压缩文件:

#!/bin/sh

 ftype=`file "$1"`
 case "$ftype" in
 "$1: Zip archive"*)
    unzip "$1" ;;
 "$1: gzip compressed"*)
    gunzip "$1" ;;
 "$1: bzip2 compressed"*)
    bunzip2 "$1" ;;
 *) echo "File $1 can not be uncompressed with smartzip";;
 esac

你可能注意到上面使用了一个特殊变量$1,该变量包含有传递给该脚本的第一个参数值。也就是说,当咱们运行:

smartzip articles.zip

$1 就是字符串 articles.zip。

[编辑] select 语句

select表达式是bash的一种扩展应用,擅长于交互式场合。用户能够从一组不一样的值中进行选择:

select var in ... ; do
 break;
done
.... now $var can be used ....

下面是一个简单的示例:

#!/bin/sh

echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do
    break;
done
echo "You have selected $var"
  1. 若是 以上脚本运行出现 select :NOT FOUND 将 #!/bin/sh 改成 #!/bin/bash 找了半天才找到的答案

该脚本的运行结果以下:

What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux

[编辑] while/for 循环

在shell中,可使用以下循环:

while ...; do
   ....
done

只要测试表达式条件为真,则while循环将一直运行。关键字"break"用来跳出循环,而关键字”continue”则能够跳过一个循环的余下部分,直接跳到下一次循环中。

for循环会查看一个字符串行表(字符串用空格分隔),并将其赋给一个变量:

for var in ....; do
   ....
done

下面的示例会把A B C分别打印到屏幕上:

#!/bin/sh

for var in A B C ; do
   echo "var is $var"
done

下面是一个实用的脚本showrpm,其功能是打印一些RPM包的统计信息:

#!/bin/sh

# list a content summary of a number of RPM packages
# USAGE: showrpm rpmfile1 rpmfile2 ...
# EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpm
for rpmpackage in $*; do
   if [ -r "$rpmpackage" ];then
      echo "=============== $rpmpackage =============="
      rpm -qi -p $rpmpackage
   else
      echo "ERROR: cannot read file $rpmpackage"dcvsdsdfasdfasdfasdfasfasf
   fi
done

这里出现了第二个特殊变量$*,该变量包含有输入的全部命令行参数值。若是你运行showrpm openssh.rpm w3m.rpm webgrep.rpm,那么 $* 就包含有 3 个字符串,即openssh.rpm, w3m.rpm和 webgrep.rpm。

[编辑] Shell里的一些特殊符号

[编辑] 引号

在向程序传递任何参数以前,程序会扩展通配符和变量。这里所谓的扩展是指程序会把通配符(好比*)替换成适当的文件名,把变量替换成变量值。咱们可使用引号来防止这种扩展,先来看一个例子,假设在当前目录下有两个jpg文件:mail.jpg和tux.jpg。

#!/bin/sh

echo *.jpg

运行结果为:

mail.jpg tux.jpg

引号(单引号和双引号)能够防止通配符*的扩展:

#!/bin/sh

echo "*.jpg"
echo '*.jpg'

其运行结果为:

*.jpg
*.jpg

其中单引号更严格一些,它能够防止任何变量扩展;而双引号能够防止通配符扩展但容许变量扩展:

#!/bin/sh

echo $SHELL
echo "$SHELL"
echo '$SHELL'

运行结果为:

/bin/bash
/bin/bash
$SHELL

此外还有一种防止这种扩展的方法,即便用转义字符——反斜杆:\:

echo \*.jpg
echo \$SHELL

输出结果为:

*.jpg
$SHELL

[编辑] Here documents

当要将几行文字传递给一个命令时,用here documents是一种不错的方法。对每一个脚本写一段帮助性的文字是颇有用的,此时若是使用here documents就没必要用echo函数一行行输出。Here document以 << 开头,后面接上一个字符串,这个字符串还必须出如今here document的末尾。下面是一个例子,在该例子中,咱们对多个文件进行重命名,而且使用here documents打印帮助:

#!/bin/sh

# we have less than 3 arguments. Print the help text:
if [ $# -lt 3 ] ; then
cat << HELP

ren -- renames a number of files using sed regular expressions USAGE: ren 'regexp' 'replacement' files...

EXAMPLE: rename all *.HTM files in *.html:
   ren 'HTM$' 'html' *.HTM

HELP
   exit 0
fi
OLD="$1"
NEW="$2"
# The shift command removes one argument from the list of
# command line arguments.
shift
shift
# $* contains now all the files:
for file in $*; do
   if [ -f "$file" ] ; then
      newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`
      if [ -f "$newfile" ]; then
       echo "ERROR: $newfile exists already"
      else
         echo "renaming $file to $newfile ..."
         mv "$file" "$newfile"
      fi
   fi
done

这个示例有点复杂,咱们须要多花点时间来讲明一番。第一个if表达式判断输入命令行参数是否小于3个 (特殊变量$# 表示包含参数的个数) 。若是输入参数小于3个,则将帮助文字传递给cat命令,而后由cat命令将其打印在屏幕上。打印帮助文字后程序退出。若是输入参数等于或大于3个,咱们 就将第一个参数赋值给变量OLD,第二个参数赋值给变量NEW。下一步,咱们使用shift命令将第一个和第二个参数从参数列表中删除,这样原来的第三个 参数就成为参数列表$*的第一个参数。而后咱们开始循环,命令行参数列表被一个接一个地被赋值给变量$file。接着咱们判断该文件是否存在,若是存在则 经过sed命令搜索和替换来产生新的文件名。而后将反短斜线内命令结果赋值给newfile。这样咱们就达到了目的:获得了旧文件名和新文件名。而后使用 mv命令进行重命名

[编辑] Shell里的函数

若是你写过比较复杂的脚本,就会发现可能在几个地方使用了相同的代码,这时若是用上函数,会方便不少。函数的大体样子以下:

functionname()
{
# inside the body $1 is the first argument given to the function
# $2 the second ...
body
}

你须要在每一个脚本的开始对函数进行声明。

下面是一个名为xtitlebar的脚本,它能够改变终端窗口的名称。这里使用了一个名为help的函数,该函数在脚本中使用了两次:

#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
cat << HELP
xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole
USAGE: xtitlebar [-h] "string_for_titelbar"
OPTIONS: -h help text
EXAMPLE: xtitlebar "cvs"
HELP
exit 0
}
# in case of error or if -h is given we call the function help:
[ -z "$1" ] && help
[ "$1" = "-h" ] && help
# send the escape sequence to change the xterm titelbar:
echo -e "33]0;$107"
#

在脚本中提供帮助是一种很好的编程习惯,能够方便其余用户(和本身)使用和理解脚本。

[编辑] 命令行参数

咱们已经见过$* 和 $1, $2 ... $9 等特殊变量,这些特殊变量包含了用户从命令行输入的参数。迄今为止,咱们仅仅了解了一些简单的命令行语法(好比一些强制性的参数和查看帮助的-h选项)。 可是在编写更复杂的程序时,您可能会发现您须要更多的自定义的选项。一般的惯例是在全部可选的参数以前加一个减号,后面再加上参数值 (好比文件名)。

有好多方法能够实现对输入参数的分析,可是下面的使用case表达式的例子无疑是一个不错的方法。

#!/bin/sh
 
help()
{
   cat << HELP
   This is a generic command line parser demo.
   USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2
HELP
   exit 0
}
  
while [ -n "$1" ]; do
case $1 in
   -h) help;shift 1;; # function help is called
   -f) opt_f=1;shift 1;; # variable opt_f is set
   -l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2
   --) shift;break;; # end of options
   -*) echo "error: no such option $1. -h for help";exit 1;;
   *) break;;
esac
done
 
echo "opt_f is $opt_f"
echo "opt_l is $opt_l"
echo "first arg is $1"
echo "2nd arg is $2"

你能够这样运行该脚本:

cmdparser -l hello -f -- -somefile1 somefile2

返回结果以下:

opt_f is 1
opt_l is hello
first arg is -somefile1
2nd arg is somefile2

这个脚本是如何工做的呢?脚本首先在全部输入命令行参数中进行循环,将输入参数与case表达式进行比较,若是匹配则设置一个变量而且移除该参数。根据unix系统的惯例,首先输入的应该是包含减号的参数。

[编辑] Shell脚本示例

[编辑] 通常编程步骤

如今咱们来讨论编写一个脚本的通常步骤。任何优秀的脚本都应该具备帮助和输入参数。写一个框架脚本(framework.sh),该脚本包含了大多数脚本须要的框架结构,是一个很是不错的主意。这样一来,当咱们开始编写新脚本时,能够先执行以下命令:

cp framework.sh myscript

而后再插入本身的函数。

让咱们来看看以下两个示例。

[编辑] 二进制到十进制的转换

脚本 b2d 将二进制数 (好比 1101) 转换为相应的十进制数。这也是一个用expr命令进行数学运算的例子:

#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
   cat << HELP
   
b2d -- convert binary to decimal
 
USAGE: b2d [-h] binarynum
 
OPTIONS: -h help text
 
EXAMPLE: b2d 111010
will return 58
HELP
   exit 0
}
 
error()
{
   # print an error and exit
   echo "$1"
   exit 1
}
 
lastchar()
{
   # return the last character of a string in $rval
   if [ -z "$1" ]; then
      # empty string
      rval=""
      return
   fi
   # wc puts some space behind the output this is why we need sed:
   numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
   # now cut out the last char
   rval=`echo -n "$1" | cut -b $numofchar`
}
 
chop()
{
   # remove the last character in string and return it in $rval
   if [ -z "$1" ]; then
      # empty string
      rval=""
      return
   fi
   # wc puts some space behind the output this is why we need sed:
   numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
   if [ "$numofchar" = "1" ]; then
      # only one char in string
      rval=""
      return
   fi
   numofcharminus1=`expr $numofchar "-" 1`
   # now cut all but the last char:
   rval=`echo -n "$1" | cut -b -$numofcharminus1` 
   #原来的 rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`运行时出错.
   #缘由是cut从1开始计数,应该是cut -b 1-${numofcharminus1}
}
 
while [ -n "$1" ]; do
case $1 in
   -h) help;shift 1;; # function help is called
   --) shift;break;; # end of options
   -*) error "error: no such option $1. -h for help";;
   *) break;;
esac
done

# The main program
sum=0
weight=1
# one arg must be given:
[ -z "$1" ] && help
binnum="$1"
binnumorig="$1"
 
while [ -n "$binnum" ]; do
   lastchar "$binnum"
   if [ "$rval" = "1" ]; then
      sum=`expr "$weight" "+" "$sum"`
   fi
   # remove the last position in $binnum
   chop "$binnum"
   binnum="$rval"
   weight=`expr "$weight" "*" 2`
done
 
echo "binary $binnumorig is decimal $sum"
#

该脚本使用的算法是利用十进制和二进制数权值 (1,2,4,8,16,..),好比二进制"10"能够这样转换成十进制:

0 * 1 + 1 * 2 = 2

为了获得单个的二进制数咱们是用了lastchar 函数。该函数使用wc –c计算字符个数,而后使用cut命令取出末尾一个字符。Chop函数的功能则是移除最后一个字符。

[编辑] 文件循环拷贝

你可能有这样的需求并一直都这么作:将全部发出邮件保存到一个文件中。可是过了几个月以后,这个文件可能会变得很大以致于该文件的访问速度变慢;下 面的脚本 rotatefile 能够解决这个问题。这个脚本能够重命名邮件保存文件(假设为outmail)为outmail.1,而原来的outmail.1就变成了 outmail.2 等等...

#!/bin/sh
# vim: set sw=4 ts=4 et:
 
ver="0.1"
help()
{
   cat << HELP
   rotatefile -- rotate the file name
   USAGE: rotatefile [-h] filename
   OPTIONS: -h help text
   EXAMPLE: rotatefile out
 
   This will e.g rename out.2 to out.3, out.1 to out.2, out to out.1[BR]
   and create an empty out-file
 
   The max number is 10
 
   version $ver
   HELP
 
   exit 0
}
 
error()
{
   echo "$1"
   exit 1
}
 
while [ -n "$1" ]; do
   case $1 in
      -h) help;shift 1;;
      --) break;;
      -*) echo "error: no such option $1. -h for help";exit 1;;
      *) break;;
   esac
done
 
# input check:
if [ -z "$1" ] ; then
   error "ERROR: you must specify a file, use -h for help"
fi
 
filen="$1"
# rename any .1 , .2 etc file:
for n in 9 8 7 6 5 4 3 2 1; do
   if [ -f "$filen.$n" ]; then
      p=`expr $n + 1`
      echo "mv $filen.$n $filen.$p"
      mv $filen.$n $filen.$p
   fi
done
 
# rename the original file:
if [ -f "$filen" ]; then
   echo "mv $filen $filen.1"
   mv $filen $filen.1
fi
 
echo touch $filen
touch $filen

这个脚本是如何工做的呢?在检测到用户提供了一个文件名以后,首先进行一个9到1的循环;文件名.9重命名为文件名.10,文件名.8重命名为文件 名. 9……等等。循环结束以后,把原始文件命名为文件名.1,同时建立一个和原始文件同名的空文件(touch $filen)

[编辑] 脚本调试

最简单的调试方法固然是使用echo命令。你能够在任何怀疑出错的地方用echo打印变量值,这也是大部分shell程序员花费80%的时间用于调试的缘由。Shell脚本的好处在于无需从新编译,而插入一个echo命令也不须要多少时间。

shell也有一个真正的调试模式,若是脚本"strangescript"出错,可使用以下命令进行调试:

sh -x strangescript

上述命令会执行该脚本,同时显示全部变量的值。

shell还有一个不执行脚本只检查语法的模式,命令以下:

sh -n your_script

这个命令会返回全部语法错误。

咱们但愿你如今已经能够开始编写本身的shell脚本了,尽情享受这份乐趣吧! :)
相关文章
相关标签/搜索