多分支的if語句
if ...; then
statement1
....
elif ...; then
statement2
...
elif ...; then
statement3
....
else
statement4
if
可以判斷腳本錯(cuò)誤的小命令
bash -n tx.sh
判斷腳本一步一步的錯(cuò)誤(一步一步執(zhí)行結(jié)果回饋)
bash -x
$ bash -x tx.sh
+ filename=/etc/passw
+ '[' '!' -e /etc/passw ']'
+ echo 'no /etc/passw'
no /etc/passw
+ exit 1
練習(xí)
如果一個(gè)文件不存在陕截,退出
如果存在驳棱,判斷為普通,或者目錄农曲,或者未知
#!/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
完成一個(gè)命令就給他踢出去
在腳本里實(shí)現(xiàn)不定義文件,文件為變量
#!/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
特殊變量
$#
變量個(gè)數(shù)乳规,1個(gè)就返回1形葬,0個(gè)文件返回為0,
所以沒有設(shè)置文件返回為0暮的,我們就可以退出腳本
$*
參數(shù)個(gè)數(shù)
#!/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
練習(xí)笙以,輸入2個(gè)變量,求和 和 乘積
#!/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]"
友情閱讀推薦:
生信技能樹公益視頻合輯:學(xué)習(xí)順序是linux冻辩,r猖腕,軟件安裝拆祈,geo,小技巧谈息,ngs組學(xué)缘屹!
B站鏈接:https://m.bilibili.com/space/338686099
YouTube鏈接:https://m.youtube.com/channel/UC67sImqK7V8tSWHMG8azIVA/playlists
生信工程師入門最佳指南:https://mp.weixin.qq.com/s/vaX4ttaLIa19MefD86WfUA
學(xué)徒培養(yǎng):https://mp.weixin.qq.com/s/3jw3_PgZXYd7FomxEMxFmw