多分支的if语句
if ...; then
statement1
....
elif ...; then
statement2
...
elif ...; then
statement3
....
else
statement4
if
可以判断脚本错误的小命令
bash -n tx.sh
判断脚本一步一步的错误(一步一步执行结果回馈)
bash -x
$ bash -x tx.sh
+ filename=/etc/passw
+ '[' '!' -e /etc/passw ']'
+ echo 'no /etc/passw'
no /etc/passw
+ exit 1
练习
如果一个文件不存在,退出
如果存在,判断为普通,或者目录,或者未知
#!/bin/bash
#
file=/etc/passwd
if [ ! -e $file ]; then
echo "no $file"
exit 1
fi
if [ -f $file ]; then
echo "$file is a common file."
elif [ -d $file ];then
echo "$file is a dir."
else
echo "unknown file."
fi
$ bash -x 11_1.sh
+ file=/etc/passwd
+ '[' '!' -e /etc/passwd ']'
+ '[' -f /etc/passwd ']'
+ echo '/etc/passwd is a common file.'
/etc/passwd is a common file.
#!/bin/bash
#
file=/etc/
if [ ! -e $file ]; then
echo "no $file"
exit 1
fi
if [ -f $file ]; then
echo "$file is a common file."
elif [ -d $file ];then
echo "$file is a dir."
else
echo "unknown file."
fi
$ ./11_1.sh
/etc/ is a dir.
位置变量,
$1
$2
...
shift
完成一个命令就给他踢出去
在脚本里实现不定义文件,文件为变量
#!/bin/bash
#
if [ -e $1 ];then
echo "OK"
else
echo "No"
fi
$ chmod +x weizhi.sh
$ ./weizhi.sh /etc/passwd
OK
$ ./weizhi.sh /etc/pas
No
#shift
#!/bin/bash
#
echo "$1"
shift
echo "$1"
shift
echo "$1"
shift
$ ./shift.sh 1 23 3
1
23
3
特殊变量
$#
变量个数,1个就返回1,0个文件返回为0,
所以没有设置文件返回为0,我们就可以退出脚本
$*
参数个数
#!/bin/bash
#
if [ $# -lt 1 ];then
echo " warnings, plz usage: ./weizhi.sh AGR1 "
exit 1
fi
if [ -e $1 ];then
echo "OK"
else
echo "No"
fi
$ ./weizhi.sh
warning plz usage: ./weizhi.sh AGR1
练习,输入2个变量,求和 和 乘积
#!/bin/bash
#
if [ $# -lt 2 ];then
echo "warnings, plz enter 2 numbers"
exit 2
fi
echo " the sum is $[$1+$2]"
echo " the pro is $[$1*$2]"
友情阅读推荐:
生信技能树公益视频合辑:学习顺序是linux,r,软件安装,geo,小技巧,ngs组学!
B站链接:https://m.bilibili.com/space/338686099
YouTube链接:https://m.youtube.com/channel/UC67sImqK7V8tSWHMG8azIVA/playlists
生信工程师入门最佳指南:https://mp.weixin.qq.com/s/vaX4ttaLIa19MefD86WfUA