Linux學習筆記(9)之Shell編程入門--判斷語句

語法一:

if [ 條件表達式 ]

then

命令序列 1

else

命令序列 2

fi

語法二:

if [ 條件表達式 ]; then

命令序列

fi

語法三:

if test 條件表達式 1

then

命令序列 1

elif [ 條件表達式 2 ]

then

命令序列 2

else

命令序列 3

fi

編寫shell腳本時,注意條件表達式與“[“ ”]“之間的空格


實例分析:
#!/bin/bash
#script4-1.sh
var1="welcome to use Shell script"
echo $var1
pwd
ls -i

#判斷當前目錄下是否存在某文件
#!bin/bash
#script4-2.sh
echo "Enter a filename"
read file
if [-f $file]
then
        echo "File $file exists."
fi

#判斷當前用戶名和輸入的用戶名是否一致
#!/bin/bash
#script4-3.sh
echo -n "Enter your login name:"
read name
if test "$name" = "$USER"
then
        echo "Hello,$name"
else
        echo "You're not $USER"
fi

#比較兩個數的大小
#!/bin/bash
#script4-4.sh
echo "Enter the first integer:"
read first
echo "Enter the second  integer:"
read second
if test "$first" -gt "$second"
    then
        echo "$first is greater than $second"
    elif test "$first" -lt "$second"
    then
        echo "$first is less than $second"
    else
        echo "$first is equal to $second"
fi


#判斷myfile文件中是否含有“GNU“字符串
#!/bin/bash
#script4-5.sh
if grep "GNU" myfile >/dev/null
then
    echo "\"GNU\" occurs in myfile"
else
echo
echo "\"GNU\"does not  occurs in myfile"
fi





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章