我正在为 Linux 终端编写 shell 脚本。我希望能够将变量输入到提示中。例如
测试.sh:
test="Monkey in the middle..."
read -p "Enter input: " input
echo $input
输出:
Enter input: $test
$test
我希望能够在脚本的 (read -p) 提示部分输入“$test”,并让脚本在末尾回显“Monkey in the middle...”而不是回显“$test”就像现在一样。
我该怎么做呢?
更新:
使用此处和 this thread 中提供给我的答案(非常感谢贡献者和评论员!),我设法拼凑出对我来说非常有效的这条线:
newvariable="$(eval echo $input)"
被告知,我被多次警告使用 eval 可能会带来安全风险。如果您选择此解决方案,请记住这一点。
最佳答案
这个问题有几个不同的答案。
如果您实际使用的是 bash
,请查看 bash(1)
手册页并阅读参数扩展部分:
If the first character of parameter is an exclamation point (
!
), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of${!prefix*}
and${!name[@]}
described below. The exclamation point must immediately follow the left brace in order to introduce indirection.
这意味着如果你有:
read $input
echo "${!input}"
然后用户输入“HOME
”,你会看到$HOME
的值。为了
例如,在我的系统上:
Enter input: HOME
/home/lars
或者,您可以使用 eval
命令,它应该可以正常工作
在任何类似 Bourne-shell 的环境中:
eval [arg ...]
The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0.
您的代码可能如下所示:
read $input
eval echo "\$$input"
shell 首先会扩展$input
的值,这样
生成的命令行——假设有人输入 HOME
对提示的响应是:
eval echo $HOME
\$
只是简单地将 $
转义为 \
以便 shell
在第一个期间不将其解释为变量的开头
通过命令行。
但是这里有个问题,考虑一下:
Enter input: ;date
$
Sun Feb 14 21:13:33 EST 2016
在这个例子中,分号导致 shell 执行一个命令, 这不一定是我们所期望或期望的。你可以 通过更好的引用来减轻这种情况:
eval echo \""$input"\"
在上面的例子中结果是:
$ sh foo.sh
Enter input: ;date
$;date
但这里的教训是“不要在安全敏感的情况下使用eval
情况。”
关于Linux shell 脚本 : Allow user to use variables in input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400137/