[英]BASH store command line arguments as separate variables
我正在編寫一個 bash 腳本,我希望能夠將每個命令行參數存儲為它自己的變量。 因此,如果有這樣的命令行:
./myscript.sh word anotherWord yetAnotherWord
結果應該是:
variable1 = word
variable2 = anotherWord
variable3 = yetAnotherWord
我試過使用 for 循環和 $@ 像這樣:
declare -A myarray
counter=0
for arg in "$@"
do
myarray[$counter]=arg
done
但是當我嘗試 echo say variable1 我得到arg[1]
而不是預期的word
任何幫助將不勝感激。
它們已經存儲在一個變量中: $@
。 您可以以$1
、 $2
等形式訪問各個索引。如果這些足夠了,您不需要將它們存儲在新變量中。
# Loop over arguments.
for arg in "$@"; do
echo "$arg"
done
# Access arguments by index.
echo "First = $1"
echo "Second = $2"
echo "Third = $3"
如果您確實想要一個新數組, args=("$@")
會一次性將它們全部分配給一個新數組。 不需要顯式的 for 循環。 然后,您可以使用${args[0]}
等訪問各個元素。
args=("$@")
# Loop over arguments.
for arg in "${args[@]}"; do
echo "$arg"
done
# Access arguments by index.
echo "First = ${args[0]}"
echo "Second = ${args[1]}"
echo "Third = ${args[2]}"
(請注意,使用顯式數組時,索引從 0 而不是 1 開始。)
我會像這樣使用一個while循環:
#!/bin/bash
array=()
counter=0
while [ $# -gt 0 ]; do
array[$counter]="$1"
shift
((counter++))
done
#output test
echo ${array[0]}
echo ${array[1]}
echo ${array[2]}
輸出是:
root@system:/# ./test.sh one two tree
one two tree
我使用計數器傳遞參數$#
和shift
這使得第一個參數$1
被刪除, $2
獲得$1
。
希望我能幫到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.