简体   繁体   English

替换成shell脚本

[英]Substitution in shell script

I like to evaluate the following in linux shell 我喜欢在linux shell中评估以下内容

CMD_6='ls'
CMD_7='ls -l'
VER=6
CMD="CMD_"$VER

I'm expecting $CMD to execute CMD_6 and list the directory content, but it is throwing an error: 我期望$CMD执行CMD_6并列出目录内容,但是会引发错误:

-bash: CMD_6: command not found

Can someone explain how to do this substitution? 有人可以解释如何进行替换吗?

Use functions. 使用功能。

cmd_6 () { ls; }
cmd_7 () { ls -l; }
ver=6
cmd="cmd_$ver"
"$cmd"

The value of cmd shouldn't be any more complicated than a single function or command name: no arguments, no other shell syntax. cmd的值不应比单个函数或命令名称更复杂:没有参数,没有其他shell语法。

... or use aliases: ...或使用别名:

$ alias cmd_6='ls'
$ ver=6
$ alias cmd="cmd_$ver"
$ alias
alias cmd='cmd_6'
alias cmd_6='ls'

The other answers explain how to to it with functions and aliases, but it can be done with variables: 其他答案解释了如何使用函数和别名来实现它,但是可以通过变量来实现:

foo="ls -l" bar=/bin/bash
$foo $bar

Output: 输出:

-rwxr-xr-x 1 root root 1099016 May 17  2017 /bin/bash

But this is a little different: 但这有点不同:

CMD="CMD_"$VER

To run it, do: 要运行它,请执行以下操作:

eval \$$CMD

Be careful with eval , only feed it known or checked input. 小心eval ,仅输入已知或检查的输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM