简体   繁体   中英

Substitution in shell script

I like to evaluate the following in 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:

-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.

... 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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