[英]BASH store command line arguments as separate variables
I am writing a bash script and I would like to be able to store each command line argument as it's own variable.我正在编写一个 bash 脚本,我希望能够将每个命令行参数存储为它自己的变量。 So if there was a command line like so:
因此,如果有这样的命令行:
./myscript.sh word anotherWord yetAnotherWord
The result should be:结果应该是:
variable1 = word
variable2 = anotherWord
variable3 = yetAnotherWord
I have tried using a for loop and $@ like so:我试过使用 for 循环和 $@ 像这样:
declare -A myarray
counter=0
for arg in "$@"
do
myarray[$counter]=arg
done
but when i try to echo say variable1 i get arg[1]
instead of the expected word
any help would be appreciated.但是当我尝试 echo say variable1 我得到
arg[1]
而不是预期的word
任何帮助将不胜感激。
They already are stored in a variable: $@
.它们已经存储在一个变量中:
$@
。 You can access the individual indices as $1
, $2
, etc. You don't need to store them in new variables if those are sufficient.您可以以
$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"
If you do want a new array, args=("$@")
will assign them all to a new array in one shot.如果您确实想要一个新数组,
args=("$@")
会一次性将它们全部分配给一个新数组。 No need for the explicit for loop.不需要显式的 for 循环。 You can then access the individual elements with
${args[0]}
and the like.然后,您可以使用
${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]}"
(Note that using an explicit array the indices start at 0 instead of 1.) (请注意,使用显式数组时,索引从 0 而不是 1 开始。)
I would use a while loop like this:我会像这样使用一个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]}
Output is:输出是:
root@system:/# ./test.sh one two tree
one two tree
I use the counter for passed arguments $#
and shift
which makes the first argument $1
get deleted and $2
gets $1
.我使用计数器传递参数
$#
和shift
这使得第一个参数$1
被删除, $2
获得$1
。
Hope i could help you.希望我能帮到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.