常用shell語法

2021-07-31 15:39:45 字數 3705 閱讀 4871

if語句

system=`uname -s`

if [ $system == "linux" ] ; then

echo

"linux"

elif [ $system == "darwin" ] ; then

echo

"darwin"

else

echo

"what?"

fi

for語句
for ((i=1; i<=10; i++))  

doecho

$done

for i in `seq 1

100`

doecho

$idone

i=1while (($i

< 100))

doecho

$i i=`expr $i + 1`

done

for i in

doecho

$idone

range="1 2 3"

for i in$do

echo

$done

range_hour="1 2 3 4 5"

for hour in

$do

range_min="02 12 22"

for min in$do

echo$$

done

done

for i in `ls ../`  

doecho

$ ls ../$

done

字串判斷
# true length>0

if [ -n "haha" ] ; then

echo

"true"

else

echo

"false"

fistr1 = str2 當兩個串有相同內容、長度時為真

str1 == str2 當兩個串有相同內容、長度時為真

str1 != str2 當串str1和str2不等時為真

-n str1 當串的長度大於0時為真(串非空)

-z str1 當串的長度為0時為真(空串)

str1 當串str1為非空時為真

數字判斷
# true 10 equal 10

if [ 10 -eq 10 ] ; then

echo "true"

else

echo "false"

fiint1 -eq int2 兩數相等為真

int1 -ne int2 兩數不等為真

int1 -gt int2

int1大於int2為真

int1 -ge int2

int1大於等於int2為真

int1 -lt int2

int1小於int2為真

int1 -le int2

int1小於等於int2為真

檔案判斷
file=`ls .`

if [ -s $ ] ; then

echo "true"

else

echo "false"

fi-r file 使用者可讀為真

-w file 使用者可寫為真

-x file 使用者可執行為真

-f file 檔案為正規檔案為真

-d file 檔案為目錄為真

-c file 檔案為字元特殊檔案為真

-b file 檔案為塊特殊檔案為真

-s file 檔案大小非0時為真

-t file 當檔案描述符(預設為1)指定的裝置為終端時為真

多個判斷邏輯合併
file=`ls .`

if [ -s

$-a -x $ ] ; then

echo

"true"

else

echo

"false"

fi-a 與

-o 或

! 非

傳參
echo

"first parameter si $1";

echo

"parameter number is $#";

echo

"all parameter $*";

# $* 只是乙個元素

echo

"-- \$* ---"

for i in

"$*"; do

echo

$idone

# $@ 表示多個引數

echo

"-- \$@ ---"

for i in

"$@"; do

echo

$idone

休眠
sleep

1 睡眠1秒

sleep

1s 睡眠1秒

sleep

1m 睡眠1分

sleep

1h 睡眠1小時

既定識別符號
$? 顯示最後命令的退出狀態。0表示沒有錯誤,其他任何值表明有錯誤。
字串操作
# 獲得字串的長度

$# 從第2個字元開始,擷取8個

$

字串切割
info='abcd;efgh'

fstr=`echo

$info | cut -d \; -f

1`sstr=`echo

$info | cut -d \; -f

2`

數字運算
s=0

#定義乙個求和變數,初值為0。

t=`expr$1**$2` #用expr改變運算順序,求x的y次方。

t=$[t*3] #t乘以3。

s=$[s+t] #結果相加。

t=$[

$1**2] #求x的平方。

t=$[t*4] #結果乘以4。

s=$[s+t] #結果相加。

t=`expr$2*5` #求5y的值。

s=$[s+t] #結果相加。

s=$[s+6] #結果加上6。

echo$s

#輸出結果。

echo$((a%b)) #取餘

陣列遍歷
#echo $  

#echo $

for data in$do

echo

$done

Shell 常用語法

bin bash 選擇編譯環境 正文 i 1 echo i 1 echo i 1echo i i2.1賦值a 5 變數定義的時候必須是等號兩邊沒有空格 b 2c a b 變數賦值 7 d a b 字串 5 2 2.2從鍵盤輸入變數值echo please input a filename read ...

Shell 常用語法

賦值 file 1 兩邊不能有空格 echo file 邏輯判斷 表示式 1 if expression then fi 兩邊必須有空格 2 if expression then fi3 if expression1 o expression2 then elif expression then e...

shell 常用語法基礎

表 31.1.萬用字元 匹配0個或多個任意字元 匹配乙個任意字元 若干字元 匹配方括號中任意乙個字元的一次出現 ls dev ttys ls ch0?doc ls ch0 0 2 doc ls ch 012 0 9 doc注意,globbing所匹配的檔名是由shell展開的,也就是說在引數還沒傳給...