shell 判断式

来源:互联网 发布:淘宝号信誉度查询 编辑:程序博客网 时间:2024/05/19 20:41

1.利用test命令的测试功能

#!/bin/bashPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATHecho "\nPlease input a filename,I will check the filename's type and permission.\n"read -p "Input a filename: " filenametest -z $filename && echo "You must input a filename." && exit 0test ! -e $filename && echo "Filename does not exist" && exit 0test -f $filename && filetype="regulare file"test -d $filename && filetype="directory"test -r $filename && perm="readable"test -w $filename && perm="$perm writable"test -x $filename && perm="$perm executable"echo "The filename: $filename is a $filetype"echo "And the permissions are : $perm"

说明: -z参数表示字符串是否为空


2.利用判断符号[]

中括号用在很多地方,包括通配符与正则表达式,所以在bash语法中使用中括号作为shell的判断式时,注意中括号的两端需要有空格符来分隔。

[空格"$HOME"空格==空格“$MAIL”空格]

在中括号内的每个组件都需要有空格键来分隔;

在中括号内的变量,最好都以双引号括号起来;

在中括号内的常量,最好都以但引号或双引号括号起来。

#!/bin/bashPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATHread -p "Please input (Y/N): " input[ "$input" == "Y" -o "$input" == "y" ] && echo "OK,continue " && exit 0[ "$input" == "N" -o "$input" == "n" ] && echo "Oh,interrupt!" && exit 0echo "I don't know what your choice is" && exit 0

说明:其中-o表示或的意思。

注意:因为ubuntu默认的sh是连接到dash的,又因为dash跟bash的不兼容所以出错了.执行时可以把sh换成bash文件名.sh来执行.成功.dash是什么东西,查了一下,应该也是一种shell,貌似用户对它的诟病颇多.


3.shell的默认变量

我们知道一个c++执行文件在运行时可以带参数,例如:./task p1 p2

同样的,脚本文件也可以带参数,且参数已经设置好变量名称了。

/path/to/scriptname opt1 opt2 opt3 opt4               $0               $1     $2   $3    $4

此外,还有一些特殊的变量可以在script内使用这些参数。

$#:代表后接的参数“个数”

$@:代表“$1”,"$2","$3","$4"之意,每个变量是独立的

$*:代表““$1c$2c$3c$4c””,其中c为分隔符,默认为空格键,

#!/bin/bash      PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin  export PATH    echo "The script name is : $0"echo "Total parameter number is : $#"[ "$#" -lt 2 ] && echo "The number of parameter is less than 2." && exit 0;echo "Your whole parameter is : '$@'"echo "The 1st parameter is: $1"echo "The 2st parameter is: $2"

shift:参数变量号码偏移


#!/bin/bash      PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin  export PATH    echo "Total parameter number is : $#"echo "Your whole parameter is : '$@'"shift   #一个变量的偏移echo "Total parameter number is : $#"echo "Your whole parameter is : '$@'"shift 3 #三个变量的偏移echo "Total parameter number is : $#"echo "Your whole parameter is : '$@'"



0 0