shell 脚本中的间接参数替换 [英] Indirect parameter substitution in shell script
问题描述
我的 shell 脚本(HP-UX 下的 POSIX shell,FWIW)有问题.我有一个名为 print_arg 的函数,我将参数名称作为 $1 传递给该函数.给定参数的名称,然后我想打印该参数的名称和值.但是,我不断收到错误消息.这是我正在尝试做的一个例子:
I'm having a problem with a shell script (POSIX shell under HP-UX, FWIW). I have a function called print_arg into which I'm passing the name of a parameter as $1. Given the name of the parameter, I then want to print the name and the value of that parameter. However, I keep getting an error. Here's an example of what I'm trying to do:
#!/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'
"
fi
}
COMMAND="XYZ"
print_arg "COMMAND"
我已尝试以我能想到的各种方式重写违规行.我咨询了当地的神谕.我检查了在线BASH 脚本指南".我磨快了那把老式的波浪刃刀,擦洗祭坛直到它闪闪发光,但后来我发现我们当地的处女供应已经减少到几乎没有.天啊!
I've tried re-writing the offending line every way I can think of. I've consulted the local oracles. I've checked the online "BASH Scripting Guide". And I sharpened up the ol' wavy-bladed knife and scrubbed the altar until it gleamed, but then I discovered that our local supply of virgins has been cut down to, like, nothin'. Drat!
任何有关如何获取其名称作为参数传递给函数的参数值的建议都将受到赞赏.
Any advice regarding how to get the value of a parameter whose name is passed into a function as a parameter will be received appreciatively.
推荐答案
您可以使用 eval
,但使用直接间接作为 SiegeX 建议 如果您可以使用 bash
可能会更好.
You could use eval
, though using direct indirection as suggested by SiegeX is probably nicer if you can use bash
.
#!/bin/sh
foo=bar
print_arg () {
arg=$1
eval argval="$$arg"
echo "$argval"
}
print_arg foo
这篇关于shell 脚本中的间接参数替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!