2020年7月16日 星期四

Linux - Shell Scripts (2)

sh vs bash

    我有時候用 sh 會讓 shell script 執行不過,通常會報 Bad substitution 之類的錯誤。其實是因為我用 ubuntu,ubuntu 的 sh 其實是指到 dash 而非 bash。dash 在這不作多介紹, 把它想像成輕量型的 bash,所以支援的功能有限,所以有機會報錯。
ubuntu: cd /bin/
ubuntu: /bin$ ls -l
lrwxrwxrwx 1 root root       4  4月  9 16:36 sh -> dash

shell 字串操作

    #!/bin/bash
    # Shell 字串操作
    # 執行 bash string.sh

        file=/dir1/dir2/dir3/my.file.txt

        # 字串刪減
        # '#' 專刪右邊
        echo ${file#*/}   # 從左邊開始批配,刪掉 / 自身和其左邊的字串:dir1/dir2/dir3/my.file.txt
        echo ${file##*/}  # 從右邊開始批配,刪掉 / 自身和其左邊的字串:my.file.txt
        echo ${file#*.}   # 從左邊開始批配,刪掉 . 自身和其左邊的字串:file.txt
        echo ${file##*.}  # 從右邊開始批配,刪掉 . 自身和其左邊的字串:txt
        # '%' 專刪右邊
        echo ${file%/*}   # 從右邊開始批配,刪掉 / 自身和其右邊的字串:/dir1/dir2/dir3
        echo ${file%%/*}  # 從左邊開始批配,刪掉 / 自身和其右邊的字串:
        echo ${file%.*}   # 從右邊開始批配,刪掉 . 自身和其右邊的字串:/dir1/dir2/dir3/my.file
        echo ${file%%.*}  # 從左邊開始批配,刪掉 . 自身和其右邊的字串:/dir1/dir2/dir3/my

        # 取子字串
        echo ${file:0:5}  # 從 index 為 0 之字元,往後取 5 個:/dir1
        echo ${file:5:5}  # 從 index 為 5 之字元,往後取 5 個:/dir2

        # 字串取代
        echo ${file/dir/path}  # 將第一個 dir 取代成 path:/path1/dir2/dir3/my.file.txt
        echo ${file//dir/path} # 將全部的 dir 取代成 path:/path1/path2/path3/my.file.txt

    exit 0

shell 陣列操作

    # Array 操作

        declare -a ARRAY      # 宣告 array 可以省略
        ARRAY=(first second third)
        echo ${ARRAY[0]}      # first
        echo ${ARRAY[1]}      # second
        echo ${ARRAY[2]}      # third
        echo ${ARRAY[*]}      # first second third
        echo ${ARRAY[*]:1:2}  # second third
        echo ${ARRAY[@]:1:2}  # second third
        
    exit 0
上一篇 :
下一篇 :

Related Posts:

  • Linux - Shell Scripts (3) (pipe : grep)管線命令 ( Pipe )     管線命令是用 "|" 去連接,只要前一資料能變成 standard input。管線命令僅會處理 standard output,而不會處理 standard error output。下面用時下最夯的 MBTI 作的假資料。 index name MBTI 1 JunYe ISTJ 2 JunYe ISTP 3 JunYe … Read More
  • Linux - Shell Scripts - ln 指令ln 指令     ln 指令是用來建立連結檔, 這裡用安裝 nodejs 示範。安裝法為在官網下載編譯好的 nodejs, 然後用 ln 建立連結檔。 # 從 nodejs.org 下載並解壓縮至 /home/user/software $ ln -s /home/daniel/software/node-v12.18.3-linux-x64/bin/node /usr/local/bin/ $ ln… Read More
  • Linux - Shell Scripts (2)sh vs bash     我有時候用 sh 會讓 shell script 執行不過,通常會報 Bad substitution 之類的錯誤。其實是因為我用 ubuntu,ubuntu 的 sh 其實是指到 dash 而非 bash。dash 在這不作多介紹, 把它想像成輕量型的 bash,所以支援的功能有限,所以有機會報錯。 ubuntu: cd /bin/ ubuntu: /bin$ ls -l lrwxrwxrwx … Read More
  • Linux - Shell Scripts (1)sh v.s source     如果直接用 sh 執行 script,基本上就是開一個子程序去執行 script。所以父程序要獲得子程序的結果,通常都是靠著 export 解決 scope 的不同。若是使用 source 去執行 script,則是直接用本身程序去執行,所以本身與腳本享有共同 scope。更多請參考 : 鳥哥私房菜。 基本的 variable & operator    … Read More

0 意見:

張貼留言

Popular Posts