1.if-then語句結構
簡單結構
if command|condition
then
commands
fi
帶else結構
if command|condition
then
commands
else
commands
fi
多層嵌套
if command|condition
then
commands
elif command|condition
then
commands
elif command|condition
then
commands
else
commands
fi
eg:
a=10
b=20
if (( "$a" < "$b" ))
then
echo "a<b"
elif (( "$a" > "$b" ))
then
echo "a>b"
else
echo "a=b"
fi
2.比較中使用(),(()),[],[[]],{}的含義與用法
首先你要理解 if 後面跟的是一個命令,而不是一個值,跟括號沒啥關係。
整個語句的執行過程是先運行if後面那個命令,如果返回0就執行then後面的語句,否則執行else後面的語句。
然後(...),((...)),[[...]]還有{...}是語法的一部分,
( ... )表示在子shell裏面執行括號裏面的命令。$( ... )表示 ... 部分運行的輸出,通常用於a=$(...)這樣的賦值語句。
(( ... ))表示括號裏面的東西是在進行數字運算,而不是當成字符串,以便你能夠用+、-、*、/、>、<這些算術運算符,同樣$(( ... ))就表示 ... 部分計算的結果。
[[ ... ]]表示裏面進行的是邏輯運算,以便你可以用&&、||這些邏輯運算符。
$[ ... ],這個是已經被廢棄的語法,跟$( ... )差不多。
至於[ ... ],它其實是一個程序 /usr/bin/[,相當於/usr/bin/test,後面多的那個]只是爲了對稱好看而已,所以[ 後面要有空格。
Shell中的 test 命令用於檢查某個條件是否成立,它可以進行數值、字符和文件三個方面的測試。
具體內容參考:https://www.cnblogs.com/rookieeee/p/12614858.html
3.讀取文件練習
-e 存在,-d 文件夾,-f 文件,-s 非空
echo 'qing shuru wenjianming'
read filename
if [ -e $filename ]
then
echo 'file exists'
fi
if [ -d $filename ]
then
echo 'file is directory'
elif [ -f $filename ]
then
echo 'file is file'
fi
if [ -s $filename ]
then
echo 'file is not empty'
fi
判斷一個文件是否是文件,如果是,判斷有無寫權限,有的話寫入東西
echo 'please input file name:'
read filename
if [ -f $filename ]
then
if [ -w $filename ]
then
echo 'qing shuru wenzi:'
cat >>$filename
else
echo 'file cannot write'
fi
else
echo '$filename is not a file'
fi
按ctrl+d退出編輯