我的shell名称是test.sh,我想输出所有传递给test.sh的参数,但是我发现我的代码无法正常工作。
#!/bin/bash
i=1
num=$#
while [ $i -le $num ]; do
echo $($i)
((i++))
done
当我运行时./test.sh -a -b -c
,我的预期输出是:
-a
-b
-c
但是,它告诉我
./test.sh: line 5: 1: command not found
./test.sh: line 5: 2: command not found
./test.sh: line 5: 3: command not found
如何解决此问题并使用echo
命令输出所有参数?
您正在寻找变量间接:
#!/bin/bash
i=1
num=$#
while [ $i -le $num ]; do
echo ${!i} # <--- print the content of $1, $2...
((i++))
done
执行后,将返回:
$ bash test.sh -a -b "-c d"
-a
-b
-c d
如果parameter的第一个字符是感叹号(!),而parameter不是nameref,则它引入了一个变量间接寻址级别。Bash使用由其余参数形成的变量的值作为变量的名称;然后扩展此变量,并在其余替换中使用该值,而不是参数本身的值。这称为间接扩展。如果parameter是nameref,则扩展为parameter引用的变量的名称,而不是执行完整的间接扩展。例外是$ {!prefix *}和$ {!name [@]}的扩展,如下所述。感叹号必须紧随左括号之后才能引入间接指示。
如果您希望使其更为冗长,请显示${1..n}
到其值的映射:
#!/bin/bash
i=1
num=$#
while [ $i -le $num ]; do
printf "$%s = %s\n" "$i" "${!i}"
((i++))
done
查看输出:
$ bash test.sh -a -b "-c d"
$1 = -a
$2 = -b
$3 = -c d
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句