Bob*_*ica 2 shell scripting posix
我遇到了shell脚本(HP-UX下的POSIX shell,FWIW)的问题.我有一个名为print_arg的函数,我将参数名称传递给$ 1.给定参数的名称,然后我想打印该参数的名称和值.但是,我一直收到错误.这是我正在尝试做的一个例子:
#!/usr/bin/sh
function print_arg
{
# $1 holds the name of the argument to be shown
arg=$1
# The following line errors off with
# ./test_print.sh[9]: argval=${"$arg"}: The specified substitution is not valid for this command.
argval=${"$arg"}
if [[ $argval != '' ]] ; then
printf "ftp_func: $arg='$argval'\n"
fi
}
COMMAND="XYZ"
print_arg "COMMAND"
Run Code Online (Sandbox Code Playgroud)
我试过以我能想到的每一种方式重写违规行.我咨询了当地的神谕.我查看了在线"BASH脚本指南".我磨了一把"波浪刀"的刀,擦了擦坛,直到它闪闪发光,但后来我发现我们当地的处女供应已经减少到了,就像没什么.讨厌鬼!
有关如何获取其名称作为参数传递给函数的参数值的任何建议都将得到认可.
在bash中(但不在其他sh实现中),间接通过以下方式完成: ${!arg}
foo=bar
bar=baz
echo $foo
echo ${!foo}
Run Code Online (Sandbox Code Playgroud)
bar
baz
Run Code Online (Sandbox Code Playgroud)
你可以使用eval
,虽然使用SiegeX建议的直接间接可能更好,如果你可以使用bash
.
#!/bin/sh
foo=bar
print_arg () {
arg=$1
eval argval=\"\$$arg\"
echo "$argval"
}
print_arg foo
Run Code Online (Sandbox Code Playgroud)