[Shell Tips] 將命令列之參數轉換成 shell 內部的變數

將命令列之參數轉換成 shell 內部的變數

$ cat test.sh
## Script parameters handling
for i in "$@"; do
    if [[ $i == *=* ]]; then
        parameter=${i%%=*}
        value=${i##*=}
        echo "Command line: setting $parameter to ${value:-(empty)}"
        eval $parameter=$value
    fi
done

$ test.sh KERNEL=new COLOR=red Loop=3 DEFAULT_VAR=
則在 test.sh 經過上面的for-loop 之後, 就會產生4個變數分別為:
KERNEL=new 
COLOR=red 
Loop=3 
DEFAULT_VAR=

參考來源: Armbian

This entry was posted in shell script and tagged . Bookmark the permalink.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *