[英]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.