Shell script 常會需要接收參數, 就會用到 argc、argv, 來寫個簡單範例.
- argc: 參數共有幾個
- argv: 取得各個參數
Shell script argv、argc 使用範例
Shell 裡面的 argc、argv 對應的變數如下:
- argc: $#
- argv: $@ (變數會存於此陣列), 由 $1, $2, $3 ... 取得各個參數(變數)
- 註: $0 為 path + script name, ex: /tmp/ex.sh
範例1
- vim ex.sh
#!/bin/bash echo "argc: $#" echo "argv 1: $1" echo "argv 2: $2" echo "argv 3: $3" echo "argv @: $@"
- chmod +x ./ex.sh
- ./ex.sh a b c
argc: 3 argv 1: a argv 2: b argv 3: c argv @: a b c
範例2
#!/bin/bash if [ $# -ne 0 ]; then while [ $# != 0 ] do echo $1 # 將每個分別印出 shift done else echo "Usage: \"./ex.sh a b c\""; exit fi
fi