beginning Linux programming读书笔记(2)之shell编程

2.Shellprogramming

 

一点哲学

UNIX建立在高度重用的基础之上

 

$ ls -al | more

说明:显示指定工作目录下之内容(列出目前工作目录所含之档案及子目录)。

 -a 显示所有档案及目录(ls内定将档案名或目录名称开头为"."的视为隐藏档,不会列出)

-l 除档案名称外,亦将档案型态,权限,拥有者,档案大小等资讯详细列出

 

你能用很多的小的脚本组成大的复杂的程序

If the utility needs to run faster, it’s quite common to prototype utilities in the shell and reimplement them later in C or C++, Perl, Python, or some other language that executes more swiftly once an idea has proven its worth.

 

什么是shell 

shell是一个程序,它作为你与操作系统之间的接口,使你能够输入命令去利用操作系统去执行。

 

管道(pipes)和重定向 

 

输出重定向

$ ls -l >lsoutput.txtls–l的命令的输出内容显示在lsoutput.txt中,如果没有这个txt则会新建它,如果已经存在则会重写这个txt,在这个txt后进行拼接的话,使用>>。

$ kill-HUP 1234  >killout.txt  2>killerr.txt 标准output将会输出在killout里,错误信息则会显示在killerr里面

 

输入重定向

$ more< killout.txt

 

管道(Pipes)

 

你可以用操作符(|)来连接进程

$ ps >psout.txt Ps:显示瞬间进程(process)的状态

$ sort psout.txt > pssort.out

可以简化为 $ ps | sort > pssort.out

 

Shell当作 是一种编程语言 

Going through this long rigmarole everytime you want to execute a sequence of commands is a bore.You need to store the commands in a file, conventionally referred to as a shell script, so you can execute them whenever you like.

 

新建一个脚本 

#!/bin/sh

# named first

for file in *

do

if grep -q POSIX $file

then

echo $file

fi

done

exit 0

 

#后是注释的内容

#!告诉操作系统它后面的程序是执行本文件的程序,/bin/shis the default shell program.

 

执行它

$/bin/sh first

太麻烦?

$ chmod+x first

$ first

Error: command not found?shell环境变量PATH没有指向当前目录,输入PATH=$PATH:即可

 

Shell语法 

 

变量 

不用声明,使用就行,默认情况下,所有的变量都被认为或者是被当作string存储

Within the shell you can access thecontents of a variable by preceding its name with a $.

salutation=”Yes Dear”

echo $salutation

Yes Dear

salutation=7+5

echo$salutation

7+5

注:如果右值有空格那么必须用“”括注。等号的两边不能有等号。

 

引号 

单引号 ’’ 以及反斜杠\将会使得变量removethe special meaning of the $ symbol,双引号则不会

myvar=”Hithere”

echo  $myvar

echo “$myvar”

echo  ‘$myvar’

echo  \$myvar

输出结果

Hi there

Hi there

$myvar

$myvar

 

环境变量

$HOME   The home directory of the current user

$PATH    A colon-separated list of directories tosearch for commands

$0       The name of the shell script

$#       The number of parameters passed

$$       The process ID of the shell script, often used inside a script for generating unique temporary filenames; for example/tmp/tmpfile_$$

 

env 命令查看当前系统的环境变量

 

参数 

 

$1, $2, …The parameters given to the script

$*       Alist of all the parameters, 被环境变量中的IFS的第一个字符分隔

$@      A list of all the parameters,与IFS无关

 

输入参数:命令后直接跟参数 例如

#!/bin/sh

salutation=”Hello”

echo $salutation

echo “The program $0 is nowrunning”

echo “The second parameter was$2”

echo “The first parameter was $1”

echo “The parameter list was $*“

echo “The user’s home directoryis $HOME”

echo “Please enter a newgreeting”

read salutation

echo $salutation

echo “The script is now complete”

exit 0

将上述语句保存为脚本文件filetemp

然后运行

$ filetemp foo bar baz

输出结果:

Hello

Theprogram ./try_var is now running

Thesecond parameter was bar

Thefirst parameter was foo

Theparameter list was foo bar baz

Theuser’s home directory is /home/rick

Pleaseenter a new greeting

Sire

Sire

Thescript is now complete

$

 

条件 

 

实际上,大部分的脚本大量应用[和test命令,它们是shell的Booleancheck

条件判断的三种类型如下:

String Comparison Result

string1 = string2   True if the strings are equal

string1 != string2   True if the strings are not equal

-n string           True if the string is not null

-z string           True if the string is null (an empty string)

 

Arithmetic Comparison Result

expression1 -eq expression2   True if the expressions are equal

expression1 -ne expression2    True if the expressions are not equal

expression1 -gt expression2   True if expression1 is greater thanexpression2

expression1 -ge expression2   True if expression1 is greater than orequal to expression2

expression1 -lt expression2     True if expression1 is less thanexpression2

expression1 -le expression2   True if expression1 is less than orequal to expression2

! expression                True if the expression isfalse, and vice versa

 

File Conditional Result

-d file   True if the file is a directory

-e file   True if the file exists.

-f file    True if the file is a regular file

-g file   True if set-group-id is set on file

-r file   True if the file is readable

-s file   True if the file has nonzero size

-u file    Trueif set-user-id is set on file

-w file    Trueif the file is writable

-x file   True if the file is executable

 

示例:

If  [  -f  /bin/bash  ]

then

 echo "file /bin/bash exists"

fi

注意[之后的空格和各种空格

控制结构 

If elif  

一个关于变量的问题 

if [ $var = 2 ] if [ “$var” = 2 ] 的不同当var为空的时候 对应的不同 尽量有括号

另外赋值的=两边不能有空格,但是比较的时候必须是有空格的

 

for语句 

for variable in values 

do

statements

done

 

示例程序: 

#!/bin/sh

#注意分号的存在 

for file in $(ls f*.sh); do

lpr $file

done

exit 0

 

while循环 

while condition do

statements

done

 

#!/bin/sh

echo“Enter password”

read trythis

while [“$trythis” != “secret” ]; do

echo“Sorry, try again”

read trythis

done

exit 0

 

until(直到…)

until condition 

do

statements

done

 

#!/bin/bash

until who | grep “$1” > /dev/null

do

sleep 60

done

# now ring the bell and announce the expected user.

echo -e‘\a’

echo“**** $1 has just logged in ****“

exit 0

Case语句 

 

#!/bin/sh

Echo  “Is it morning? Please answer yes or no”

read  timeofday

case  “$timeofday”  in

yes | y| Yes | YES )  echo “Good Morning”;;

n* | N*)  echo “Good Afternoon”;;

* )  echo “Sorry, answer not recognized”;;

esac

exit 0

注意:分开符;;匹配的更全面:[yY]| [Yy][Ee][Ss] )


ANDList&&

例子: 

#!/bin/sh

touchfile_one

rm -ffile_two

if [ -ffile_one ] && echo “hello” && [ -f file_two ] && echo “there”

then

echo“in if”

else

echo“in else”

fi

exit 0

 

执行结果:

hello

in else

 

注意两点 1. 短路闭合特性2. Echo返回值为true

 

OR List基本同上 ||


posted @ 2010-11-23 17:37  樱色布  阅读(449)  评论(0编辑  收藏  举报