next up previous contents
Next: 變數的設定 Up: Shell 變數 Previous: 陣列   Contents

變數的變化與取代

  1. 兩種變數取用的方法:
    [root@deyu ~]# echo $HOME
    [root@deyu ~]# echo ${HOME}
    
  2. 完整變數的內容;
    [dywang@dywH ~]$ blkid /dev/sda1
    /dev/sda1: UUID="716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4" 
    [dywang@dywH ~]$ uuid=$(blkid /dev/sda1);echo $uuid
    /dev/sda1: UUID="716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4"
    
  3. 從最前面開始比對,刪除符合的字元。
    [dywang@dywH ~]$ uuid=${uuid#*=\"}; echo $uuid
    716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4"
    [dywang@dywH ~]$ uuid=$(blkid /dev/sda1);echo $uuid
    /dev/sda1: UUID="716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4"
    [dywang@dywH ~]$ uuid=${uuid##*=\"}; echo $uuid
    ext4"
    # 變數名稱後面如果接了兩個 ## ,表示在 ## 後面的字串取『最長的』那一段;
    # 如果僅有一個 # ,表示取『最小的那一段』。
    
  4. 從後面開始比對並刪除:
    [dywang@dywH ~]$ uuid=$(blkid /dev/sda1);echo $uuid
    /dev/sda1: UUID="716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4"
    [dywang@dywH ~]$ uuid=${uuid%%\"*}; echo $uuid
    /dev/sda1: UUID=
    # %% 刪除最長的匹配,% 則是最短的匹配。
    
  5. 取代變數部分字串
    [dywang@dywH ~]$ uuid=$(blkid /dev/sda1);echo $uuid
    /dev/sda1: UUID="716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4"
    [dywang@dywH ~]$ uuid=${uuid%\"*}; echo $uuid
    /dev/sda1: UUID="716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4
    [dywang@dywH ~]$ uuid=$(blkid /dev/sda1);echo $uuid
    /dev/sda1: UUID="716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4"
    [dywang@dywH ~]$ uuid=$(blkid /dev/sda1);echo ${uuid/=/:}
    /dev/sda1: UUID:"716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE="ext4"
    [dywang@dywH ~]$ uuid=$(blkid /dev/sda1);echo ${uuid//=/:}
    /dev/sda1: UUID:"716a2ac8-517e-41e4-a139-c2bc12b3dd5f" TYPE:"ext4"
    # 變數後面接 / 時,表示進行『取代』的工作,且僅取代『第一個』
    # 如果是 // ,則表示全部的字串都取代。
    
  6. 例題:請取出uuid編號,不含雙引號。



2017-06-14