您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
马哥linux运维学习笔记-bash脚本编程之四 整数测试及特殊变量
发布时间:2018-06-24 20:53:38编辑:雪饮阅读()
关于脚本中的exit
exit命令在脚本中用于终止该命令之后命令的执行,直接使得脚本停止运行并退出
该命令在退出后会有输出状态值,状态值作为参数可以自定义,若没有自定义则会将exit命令之前最后执行的语句的状态值做为退出脚本后的状态值
状态值即状态码,这里状态码可选为0-255
0表示正确,1-255表示错误
一个判断用户是否存在的小脚本:
#!/bin/bash
username=$1
if ! grep "^$1\>" /etc/passwd &> /dev/null; then
echo "no user"
exit 1
fi
文件测试
在脚本中测试语法中文件测试语法如下:
-e FILE:测试文件是否存在
-f FILE:测试文件是否为普通文件
-d FILE:测试指定路径是否为目录
-r FILE:测试当前用户对指定文件是否有读取权限
-w FILE:测试当前用户对指定文件是否有写入权限
-x FILE:测试当前用户对指定文件是否有执行权限
一个文件测试小脚本
#!/bin/bash
file=$1
if ! [ -e $file ]; then
echo "file no such"
exit 1
fi
if [ -f $file ] then
echo "ordinary file $file"
fi
if [ -d $file ] then
echo "$file is dir"
fi
if [ -r $file ] then
echo "current user read $file is ok"
fi
if [ -w $file ] then
echo "current user write $file is ok"
fi
if [ -x $file ] then
echo "current user excute $file is ok"
fi
bash -n与bash -x
前者是对脚本错误(关键性错误)的检查
后者是对脚本单步执行的记录,即对该脚本的执行明细,便于分析调试该脚本。
bash -n his.sh
bash -x his.sh
特殊变量
$#特殊变量用来获取当前脚本所接受到的参数个数
$*和$@都是获取当前脚本所接收到的参数列表
shift用来轮替脚本所接收的参数列表
比如你的脚本要接收3个参数,
当脚本中shift执行第一次后$1就变成了实际参数的第二个参数
当脚本中shift执行第二次时$1就变成了实际参数的第三个参数
也就是说从参数列表由左至右剔除参数
shift还可以带参数,比如shift 2就代表一次性剔除2个参数
特殊变量小脚本
#!/bin/bash
echo "current script args num is $#"
echo "current script args list is: $*"
echo "current script args list is: $@"
shift
echo "current script args shift num 1 after args list is: $@"
shift 2
echo "current script args also shift num 2 after args list is: $@"
一个计算参数之和与计算参数之积的小脚本
#!/bin/bash
if [ $# -lt 2 ]; then
echo arg lt 2
exit 1
fi
sum=$[$1+$2]
cal=$[$1*$2]
echo "2 arg sum is $sum"
echo "2 arg cal is $cal"
关键字词:bash,整数测试,特殊变量