1. 程式人生 > >linux shell 程式設計之if(收藏學習)

linux shell 程式設計之if(收藏學習)

if 語句格式
if  條件
then
 Command
else
 Command
fi                             別忘了這個結尾
If語句忘了結尾fi
test.sh: line 14: syntax error: unexpected end of fi


    if 的三種條件表示式
if
command
then

if
 函式
then
 命令執行成功,等於返回0 (比如grep ,找到匹配)
執行失敗,返回非0 (grep,沒找到匹配)
if [ expression_r_r_r  ]
then 
 表示式結果為真,則返回0,if把0值引向then
if test expression_r_r_r
then
 表示式結果為假,則返回非0,if把非0值引向then

     
   [ ]&& ——快捷if
[ -f "/etc/shadow" ] && echo"This computer uses shadow passwors"
   &&可以理解為then
   如果左邊的表示式為真則執行右邊的語句
 

    shell的if與c語言if的功能上的區別
 shell if    c語言if
0為真,走then  正好相反,非0走then
 不支援整數變數直接if
必須:if [ i –ne 0 ]

但支援字串變數直接if
if [ str ] 如果字串非0
 支援變數直接if
if (i )

 
=================================以command作為if條件===================================
  
    以多條command或者函式作為if 條件
echo –n “input:”
read user

if
多條指令,這些命令之間相當於“and”(與)
grep $user /etc/passwd>/tmp/null      
who -u | grep $user
then            上邊的指令執行成功,返回值$?為0,0為真,執行then
 echo "$user has logged"
else    指令執行失敗,$?為1,執行else                           
 echo "$user has not logged"
fi   
# sh test.sh
input : macg
macg    pts/0       May 15 15:55  .         2075 (192.168.1.100)
macg has logged
   
# sh test.sh
input : ddd
ddd has not logged  


    以函式作為if條件 (函式就相當於command,函式的優點是其return值可以自定義)
if
以函式作為if條件,
getyn
then   函式reture值0為真,走then
echo " your answer is yes"
else  函式return值非0為假,走else
echo "your anser is no"
fi  


   if command  等價於 command+if$?
$ vi testsh.sh
#!/bin/sh

if
cat 111-tmp.txt | grepting1
then
echo found
else
echo "no found"
fi
 $ vi testsh.sh
#!/bin/sh

cat 111-tmp.txt | grepting1

if [ $? -eq 0 ]
then
echo $?
echo found
else
echo $?
echo "no found"
fi
$ sh testsh.sh
no found  
$ sh testsh.sh
1
no found
$ vi 111-tmp.txt
that is 222file
thisting1 is 111file

$ sh testsh.sh
thisting1 is 111file
found
$ vi 111-tmp.txt
that is 222file
thisting1 is 111file

$ sh testsh.sh
thisting1 is 111file
0
found

   
========================================以條件表示式作為if條件=============================

    傳統if 從句子——以條件表示式作為 if條件
if [ 條件表示式 ]
then
 command
 command
 command
else
 command
 command
fi
   
  條件表示式
  • 檔案表示式
if [ -f  file]   如果檔案存在
if [ -d...  ]   如果目錄存在
if [ -s file ]   如果檔案存在且非空 
if [ -r file ]   如果檔案存在且可讀
if [ -w file  ]   如果檔案存在且可寫
if [ -x file  ]   如果檔案存在且可執行  
  • 整數變量表達式
if [ int1 -eq int2]   如果int1等於int2   
if [ int1 -ne int2]    如果不等於   
if [ int1 -ge int2]      如果>=
if [ int1 -gt int2]      如果>
if [ int1 -le int2]      如果<=
if [ int1 -lt int2]      如果<
   
  •    字串變量表達式
If  [ $a = $b]                如果string1等於string2
                               字串允許使用賦值號做等號
if  [ $string1 !=  $string2]  如果string1不等於string2       
if  [ -n$string ]           如果string 非空(非0),返回0(true) 
if  [ -z $string ]            如果string 為空
if  [ $sting]                如果string非空,返回0 (和-n類似)   


    條件表示式引用變數要帶$
if [ a = b ];then    
echo equal
else
echo no equal
fi
[[email protected] ~]$ sh test.sh
input a:
5
input b:
5
no equal (等於表示式沒比較$a和$b,而是比較和a和b,自然a!=b)
改正:
if [ $a = $b ];then       
echo equal
else
echo no equal
fi
[[email protected] ~]$ sh test.sh
input a:
5
input b:
5
equal

                                                                                   
  -eq  -ne -lt  -nt只能用於整數,不適用於字串,字串等於用賦值號=
[[email protected] ~]$ vi test.sh
echo -n "input your choice:"
read var
if  [ $var -eq "yes" ]
then
echo $var
fi
[[email protected] ~]$ sh -x test.sh
input your choice:
y
test.sh: line 3: test: y: integerexpression_r_r_r expected
                      期望整數形式,即-eq不支援字串



    =放在別的地方是賦值,放在if [ ]裡就是字串等於,shell裡面沒有==的,那是c語言的等於


   無空格的字串,可以加" ",也可以不加
[[email protected] ~]$ vi test.sh
echo "input a:"
read a
echo "input is $a"
if [ $a = 123 ] ; then
echo equal123
fi
[[email protected] ~]$ sh test.sh
input a:
123
input is 123
equal123 


    =作為等於時,其兩邊都必須加空格,否則失效
等號也是操作符,必須和其他變數,關鍵字,用空格格開 (等號做賦值號時正好相反,兩邊不能有空格)
[[email protected] ~]$ vi test.sh

echo "input your choice:"
read var
if [ $var="yes" ]
then
echo $var
echo "input is correct"
else
echo $var
echo "input error"
fi
[[email protected] ~]$ vi test.sh

echo "input your choice:"
read var
if [ $var = "yes"]   在等號兩邊加空格
then
echo $var
echo "input is correct"
else
echo $var
echo "input error"
fi
[[email protected] ~]$ sh test.sh
input your choice:
y
y
input is correct
[[email protected] ~]$ sh test.sh
input your choice:
n    
n
input is correct 
輸錯了也走then,都走then,為什麼?
因為if把$var="yes"連讀成一個變數,而此變數為空,返回1,則走else
 [[email protected] ~]$ sh test.sh
input your choice:
y
y
input error
[[email protected] ~]$ sh test.sh
input your choice:
no                       
no
input error
一切正常


    If [  $ANS ]    等價於  if [ -n $ANS ]
     如果字串變數非空(then) , 空(else)
echo "input your choice:"
read ANS

if [ $ANS ]
then
echo no empty
else
echo empth
fi 
[[email protected] ~]$ sh test.sh
input yourchoice:                   回車
                                                
empth                                   說明“回車”就是空串
[[email protected] ~]$ sh test.sh
input your choice:
34
no empty 

 
    整數條件表示式,大於,小於,shell裡沒有> 和<,會被當作尖括號,只有-ge,-gt,-le,lt
[[email protected] ~]$ vi test.sh

echo "input a:"
read a
if  [ $a -ge 100 ] ; then
echo 3bit
else
echo 2bit
fi
[[email protected] ~]$ sh test.sh
input a:
123
3bit
[[email protected] ~]$ sh test.sh
input a:
20
2bit


 整數操作符號-ge,-gt,-le,-lt, 別忘了加-
if  test $a  ge 100 ; then

[[email protected] ~]$ sh test.sh
test.sh: line 4: test: ge: binary operator expected
if  test $a -ge 100 ; then

[[email protected] ~]$ sh test.sh
input a:
123
3bit


============================邏輯表示式=========================================
   邏輯非!                  條件表示式的相反
if [ ! 表示式 ]
if [ ! -d $num]                      如果不存在目錄$num


   邏輯與–a                   條件表示式的並列
if [ 表示式1  –a  表示式2 ]


    邏輯或-o                   條件表示式的或
if [ 表示式1  –o 表示式2 ]

  
   邏輯表示式

  •    表示式與前面的=  != -d –f –x -ne -eq -lt等合用
  •    邏輯符號就正常的接其他表示式,沒有任何括號( ),就是並列
if [ -z "$JHHOME" -a -d $HOME/$num ]
  •    注意邏輯與-a與邏輯或-o很容易和其他字串或檔案的運算子號搞混了


  最常見的賦值形式,賦值前對=兩邊的變數都進行評測
左邊測變數是否為空,右邊測目錄(值)是否存在(值是否有效)
[[email protected] ~]$ vi test.sh
:
echo "input the num:"
read num
echo "input is $num"

if [ -z "$JHHOME" -a -d $HOME/$num]  如果變數$JHHOME為空,且$HOME/$num目錄存在
then
JHHOME=$HOME/$num                    則賦值
fi

echo "JHHOME is$JHHOME"  
-----------------------
[[email protected] ~]$ sh test.sh
input the num:
ppp
input is ppp
JHHOME is

目錄-d$HOME/$num  不存在,所以$JHHOME沒被then賦值
[[email protected] ~]$ mkdir ppp
[[email protected] ~]$ sh test.sh
input the num:
ppp
input is ppp
JHHOME is /home/macg/ppp


   一個-o的例子,其中卻揭示了”=”必須兩邊留空格的問題
echo "input your choice:"
read ANS

if [ $ANS="Yes" -o$ANS="yes" -o $ANS="y" -o $ANS="Y" ]
then
ANS="y"
else
ANS="n"
fi

echo $ANS
[[email protected] ~]$ sh test.sh
input your choice:
n
y
[[email protected] ~]$ sh test.sh
input your choice:
no
y
為什麼輸入不是yes,結果仍是y(走then)
因為=被連讀了,成了變數$ANS="Yes",而變數又為空,所以走else了

[[email protected] ~]$ vi test.sh

echo "input your choice:"
read ANS    echo"input your choice:"
read ANS

if [ $ANS = "Yes" -o $ANS ="yes" -o $ANS = "y" -o $ANS = "Y" ]
then
ANS="y"
else
ANS="n"
fi

echo $ANS
[[email protected] ~]$ sh test.sh
input your choice:
no
n
[[email protected] ~]$ sh test.sh
input your choice:
yes
y
[[email protected] ~]$ sh test.sh
input your choice:
y
y


===================以  test 條件表示式作為if條件===================================

    if test $num -eq0     等價於   if [ $num –eq 0]

    test 表示式,沒有 [  ]
if test $num -eq0                
then
echo "try again"
else
echo "good"
fi

   man test
[[email protected] ~]$ man test
[(1)                            UserCommands                           [(1)

SYNOPSIS
      test EXPRESSION
      [ EXPRESSION ]


      [-n] STRING
             the length of STRING isnonzero         -n和直接$str都是非0條件

      -z STRING
             the length of STRING is zero

      STRING1 = STRING2
             the strings are equal

      STRING1 != STRING2
             the strings are not equal

      INTEGER1 -eq INTEGER2
             INTEGER1 is equal to INTEGER2

      INTEGER1 -ge INTEGER2
             INTEGER1 is greater than or equal to INTEGER2

      INTEGER1 -gt INTEGER2
             INTEGER1 is greater than INTEGER2

      INTEGER1 -le INTEGER2
             INTEGER1 is less than or equal to INTEGER2

      INTEGER1 -lt INTEGER2
             INTEGER1 is less than INTEGER2

      INTEGER1 -ne INTEGER2
             INTEGER1 is not equal to INTEGER2

      FILE1 -nt FILE2
             FILE1 is newer (modification date) than FILE2

      FILE1 -ot FILE2
             FILE1 is older than FILE2

      -b FILE
             FILE exists and is block special

      -c FILE
             FILE exists and is character special

      -d FILE
             FILE exists and is a directory

      -e FILE
             FILEexists                                檔案存在

      -f FILE
             FILE exists and is a regularfile    檔案存在且是普通檔案

      -h FILE
             FILE exists and is a symbolic link (same as -L)

      -L FILE
             FILE exists and is a symbolic link (same as -h)

      -G FILE
             FILE exists and is owned by the effective group ID

      -O FILE
             FILE exists and is owned by the effective user ID

      -p FILE
             FILE exists and is a named pipe


      -s FILE
             FILE exists and has a size greater than zero

      -S FILE
             FILE exists and is a socket

      -w FILE
             FILE exists and is writable

      -x FILE
FILE exists and is executable
 


======================if簡化語句=================================

    最常用的簡化if語句
   &&如果是“前面”,則“後面”
[ -f /var/run/dhcpd.pid ] && rm/var/run/dhcpd.pid   檢查 檔案是否存在,如果存在就刪掉
   ||  如果不是“前面”,則後面
[ -f /usr/sbin/dhcpd ] || exit0   檢驗檔案是否存在,如果存在就退出
 
    用簡化 if 和$1,$2,$3來檢測引數,不合理就呼叫help
[ -z "$1" ]&&help               如果第一個引數不存在(-z  字串長度為0 )
[ "$1" = "-h" ] &&help                      如果第一個引數是-h,就顯示help


例子
#!/bin/sh

[ -f "/etc/sysconfig/network-scripts/ifcfg-eth0" ]&& rm -f/etc/sysconfig/network-scripts/ifcfg-eth0
cp ifcfg-eth0.bridge/etc/sysconfig/network-scripts/ifcfg-eth0

[ -f "/etc/sysconfig/network-scripts/ifcfg-eth1" ]&& rm -f/etc/sysconfig/network-scripts/ifcfg-eth1
cp ifcfg-eth1.bridge/etc/sysconfig/network-scripts/ifcfg-eth1

[ -f "/etc/sysconfig/network-scripts/ifcfg-eth0:1" ]&& rm -f/etc/sysconfig/network-scripts/ifcfg-eth0:1

轉載自:http://blog.sina.com.cn/s/blog_6151984a0100ekl6.html


相關推薦

linux shell 程式設計if(收藏學習)

if 語句格式if  條件 then  Command else  Commandfi                             別忘了這個結尾 If語句忘了結尾fi test.sh: line 14: syntax error: unexpected end

Linux Shell程式設計 for迴圈語句 if條件語句

    最近涉及Linux Shell程式設計,還不太熟悉,對於賦值語句,數值計算,迴圈語句,變數使用都不太熟悉。我不打算一個一個的說明知識點,我打算用最多3個例子說明所有的這些知識點。 Example 1 : <span style="font-size:14px;

Linux 下的 shell 程式設計 if-else選擇結構

 Linux 中 shell 中if else 的使用方式比較簡單,. 相關的關鍵字有: if, elif , else, fi, 等.   1. if 的判斷表示式是 []   2. if 的範圍

Shell程式設計if簡單判斷兩個數字大小

#指令碼編輯   #!/bin/bash #定義變數 num1=$1 num2=$2   #判斷是否輸入兩個引數,若是,將兩個引數傳遞給下一個指令動作,若非兩個引數,則列印輸出內容輸出並且退出exit指令碼不執行下一個指令 if [ $# -ne

linux shell程式設計利用環境變數IFS自定義分隔符

預設情況下,bash shell將空格符、製表符、換行符看作是欄位分隔符,如果遇到這些字元,bash shell就會認為字元後是一個新的欄位,這就帶來一種困擾:如果我們想處理包含空格、製表符、換行符的字元就會有麻煩了。bash提供了一種自定義分隔符的機制:環境變數IFS定義

Shell程式設計IF條件語句各種案例演練

3. if條件語句學習 案例一,測試數字的大小 #!/bin/sh NUM=100 if(($NUM > 4)) ; thenecho "this num is $NUM greater 4 !"fi 必須以fi結尾 9.檔名為 if.sh #!/bin/sh #

Linux-shell程式設計bash變數

Bash變數命名規則 必須以字母下劃線開頭,只能由字母下劃線數字組成。 長度不能超過255個字元 變數名在有效的範圍內必須唯一 在Bash中,變數的預設型別都是字串 一 使用者自定義變數 使用者自定

Linux-Shell程式設計建立shell指令碼並執行

1、建立檔案 touch myFirst.sh 2、編輯檔案 vi myFirst.sh 點選鍵盤的字母 I 進行編輯,輸入一下內容 #!/bin/bash # M

linux中的shell程式設計變數

shell程式設計主要是為了簡化linux系統管理的。 shell中的變數是一種弱型別的變數,c,java等語言是一種強型別的語言。 linux中的所有的變數預設型別都是字元型別的 零、bash變數的分類 bash變數的型別 變數型別

linux中的shell程式設計while迴圈和until迴圈

while迴圈語法: while [ 條件判斷式 ] do 程式語句 條件終止語句 done 例項:求1加到100的和 #!/bin/bash #!從1加到100 i=1 s=0 while [ $i -le 100 ] # 如果變數i

linuxshell 程式設計擴充套件正則表示式

1. ‘+’ 限定字元 +限定符表示前面字元至少出現一次或者多次。與*不同在於0次或者多次 2. '?' 限定符 ?限定前面的字元最多出現一次。即出現0次或者1次 3. 數線 |和圓括號() 例如

Linux shell程式設計——if條件判斷

if 語句格式if  條件then Commandelse Commandfi                              別忘了這個結尾If語句忘了結尾fitest.sh: line 14: syntax error: unexpected end of fi

學習Linux C程式設計語句

一、空語句 由分號“;”構成,作用:1.消耗cpu,起延時作用 2.使程式結構清楚,可讀性好 二、基礎語句 1.表示式+; 2.函式名+; 三、語句if     注意:1.不可將布林量直接與TRUE、FALSE或者1、0作比較,例如VC++將TRUE定義為1,而VB將TUR

linuxshell 程式設計變數及數學運算

1.shell中的變數是不分資料型別的,統一按照字串來儲存 2. bash shell只能支援數學整數運算(zsh可以支援浮點) 3.以下都是在bash shell 下進行的數學運算 方法一使用方括號進行基本的整數運算: #!/bin/bash var1=1 var2=2

linux基本操作---shell程式設計 while迴圈

java中我們經常用到while迴圈,那麼shell中也有while迴圈: while簡單迴圈 直接看demo: demo1: 求1-10的和 [[email protected]02 software]# cat while1to10.sh

學習Linux C程式設計語句 問題-break和continue

break和continue都是用來控制迴圈結構的,主要是停止迴圈。 1.break 有時候我們想在某種條件出現的時候終止迴圈而不是等到迴圈條件為false才終止。 這是我們可以使用break來完成。 break用於完全結束一個迴圈,跳出迴圈體執行迴圈後面的語句。

學習Linux C程式設計程序控制程式設計

建立程序 fork fork 的定義 在 Linux 中,我們使用 fork 來建立一個子程序 fork 的返回值 fork 函式有些特殊,成功它返回 2 次,失敗返回 -1,利用這個特性可以判斷當前的程序是子程序還是父程序:  1. 在子程序中返回 0  2.

linux shell程式設計學習--字串的使用和操作

在bash shell的使用過程中,經常會遇到一些字串string的操作,下面是個人的一些使用總結。 一、字串的定義 用雙引號,單引號,或者直接在接在=後,都可以定義一個字串,如下,定義了三個字串 str1="this is a string"

學習Linux C程式設計預處理與結構體

結構體的一般定義形式為:  struct 結構體名{     型別名1 成員名1;     型別名2 成員名2;     ……     型別名n 成員名n;    }; struct是關鍵字,是結構體型別的標誌。例如,定義一個Carstruct Car {    int wheels; // 輪子數    i

學習Linux C程式設計陣列與指標

1.    指標型別分析 分析指標,可以從變數名處起,根據運算子優先順序結合,一步一步分析. int p;  //這是一個普通的整型變數 int *p;  //首先從P處開始,先與*結合,所以說明P是一個指標,然後再與int結合,說明指標所指向的內容的型別為int 型.所以