SHELL [编程]

来源:互联网 发布:甜品软件 编辑:程序博客网 时间:2024/05/16 08:07

     【条件测试】    

测试文件状态

test condition    

[condition]

常用 -d 目录 -w 可写  -f 正规文件 -r可读  -s 非空 -x可执行

$test -w scores.txt

$echo $?

0

$[ -x scores.txt ]

$ echo $?

1

$[ -d appsbin ]

$echo $?

0

逻辑操作符

-a 逻辑与,均为真,结果为真; -o 一边为真,结果为真; !

$[ -w results.txt -a -w scores.txt ]

$ echo $?

0

$ [ -x results.txt -o -x scores.txt ]

$ echo $?

0

字符串测试

test "string"

test string_operaor "string"

test "string" string_operator "string"

[ string_operator string ]

[ string string_operator string ]

=     !=   -z 空串  -n非空船

$ [ -z $EDITOR ]

$echo $?

0

$ [ "$TAPE1" = "$TAPE2" ]

$ echo $?

0

数值测试

"number" numberic_operator "number"

或者

[ "number" numberic_operator "number" ]

-eq     -ne不相等    -gt 大于  -lt小于   -le 小于等于   -ge 大于等于

$ [ "NUMBER" -eq "130" ]

$ echo $?

0

$ [ "990" -le "995" -a "123" -gt "33" ]

$ echo $?

0

expr

expr argument operator argument

$expr 10+10

20

0

$expr 30 /3 /2

5

$ expr 30 \* 3

90

$ counter=`expr $counter + 1`

   控制流结构

流控制:

if  条件1

    then 命令1

elif 条件2

    then  命令2

else 命令3

fi

--------------------------------------------

if 条件; then          if 条件

    命令                   then 命令

fi                             fi

if grep 'Dave\>' datalfile > /dev/null 2>&1       查看Dave是否在文件data.file中

if cp myfile myfile.bak                          拷贝文件是否正常

if [ "$PWD" != "/" ]              当前目录测试

if [ ! -w "$LOGFILE" ]           文件权限测

if cp  $1 $2 > /dev/null 2>&1 

      then :

      else

case 值 in

      模式1 )

             命令1

               ;;

      模式2)

             命令2

               ;;

      *)

             命令3

            exit 1

               ;;

esac

循环

for  变量名 in 列表

do

      命令1

      命令2 ...

done

for loop in 1 2 3 4 5   [ for loop in “orange apple banana"]  [ for loop in `ls ` ]

do

     echo $loop

done

for params [ for params in "$@"]   命令行位置参数作为参数

do

     echo $params

done


util 条件

      命令1

      ...

done

LOOK_OUT=`df | grep /logs | awk '{print $5}' | sed 's/%//g}'`

echo $LOOK_OUT

until [ "$LLO_OUT" -gt "90" ]

do

   echo "Filesystem..lngs is nearly full" |mail root

   exit 0

done

while 条件

do

      命令1

      命令2

done

while read LINE

do

    echo $LINE

done <$names.txt   读文件

   函数

[function] 函数名()

{

命令

}

定义和使用函数

hello(){

     echo "hello world!"

}

hello

函数中使用参数,像在一般脚本中使用特殊变量$1,$2...$9

函数返回

return 1

return 0


原创粉丝点击