1. 程式人生 > >Shell實戰訓練營Day7

Shell實戰訓練營Day7

檔案目錄屬性判斷
[ -f file ] 判斷是否為普通檔案,且存在
[ -d dir ] 判斷是否為目錄,且存在
[ -e file ] 判斷檔案或目錄是否存在
[ -r file ] 判斷檔案是否可讀
[ -w file ] 判斷檔案是否可寫
[ -x file ] 判斷檔案是否可執行*
[ ! -f file ] 取反 表示不存在

if的特殊用法
if [ -z "$a" ] 表示當變數a的值為空
if [ -n "$a" ] 表示當變數a的值不為空
if grep -wq 'word' file;then..... if可以結合其他命令使用,本列表示 若file檔案中有包含word的行
if [ ! -e file ] ; then.... 表示問價不存在的時候執行then....
if (($a<1)) ; then.....等同於 if [ $a -lt 1 ];then.....
[ ] 中部支援 < ,>, >=,<=,!=,==符號 可以使用 lt gt le ge ne eq

case 用法
格式
case 變數名 in
value1)
command
;;
value2)
command
;;
.*)
command
;;
esac
在case程式中,可以在條件中使用 | 邏輯關係
條件1|條件2)
;;

case 用法舉例
#!/bin/bash
read -p "please input a number :"  n    # 輸入並捕獲
if [ -z "$n" ]
then
            echo "please input a number."
            exit 1

fi
n1=echo $n|sed 's/[0-9]//g' #將變數n中全部數字替換為空然後賦值給n1
if [ ! -z "$n1" ] # 判斷n1是否為空 此舉判斷輸入是否為純數字
then
echo "please input a number."
exit 1
fi
if [ $n -lt 60 ] &&[ $n -gt 0 ]
then
tag=1
elif [ $n -gt 60 ] && [ $n -lt 80 ]
then
tag=2
elif [ $n -gt 80 ] && [ $n -lt 90 ]
then
tag=3
elif [ $n -gt 90 ] && [ $n -le 100 ]
then
tag=4
else
tag=0
fi

case $tag in
1)
echo bjige
;;
2)
echo jige
;;
3)
ehco lianghao
;;
4)
echo youxiu
.*)
echo "please input number rage 1-100"
esac

for  迴圈

語法
for 變數名 in 條件;do.....;done

舉例
#!/bin/bash
sum =0
for i in seq 1 100
do
sum=$[$sum+$i]
done
echo sum

舉例
#!/bin/bash
cd /etc
for a in ls /etc/
do
if [ -d $a ]
then
ls $a
fi
done