1

Is it possible to execute multiple commands stored in a variable? Singe command works fine

variable="echo HELLO"
$variable

HELLO

I would like to have something like this

variable="echo HELLO; echo WORLD"

HELLO

WORLD

not

HELLO; echo WORLD

  • @jesse_b Yes, thank you. All I needed was 'eval $cmd' instead of plain '$cmd'. –  Sep 23 '22 at 14:28
  • That is probably not what you should have concluded after reading the duplicate. – jesse_b Sep 23 '22 at 14:39
  • What would be the correct conclusion then? –  Sep 23 '22 at 15:40
  • 1
    The correct conclusion, IMO, is that there is almost never a reason to store a command in a variable. This could be a function or even an alias – jesse_b Sep 23 '22 at 15:41
  • Yes, I understand and agree with that, but this time I have a reason ;) –  Sep 23 '22 at 16:52

1 Answers1

0

you need to use arrays (which is not really a single variable...)

cmds_array+=( 'echo "Hello"' )
cmds_array+=( 'echo "World ..."' )
for cmd in "${cmds_array[@]}"; do $cmd ; done

or: parse your variable with awk (but may be less portable: lots of things could contain a ";" and not be a command separator....)

execute_all_cmds () {
  awk -v cmds="${1}" '
     BEGIN { n=split(cmds, cmd, ";")
             for(i=1; i<=n; i++) { system( cmd[i] ) }
      } '
}

cmds='echo "hello" ; echo "World"'

execute_all_cmds "$cmds"

  • do $cmd applies split+glob on $cmd and executes the resulting words as a simple command, so assuming an unmodified $IFS, echo "Hello" output "Hello" not Hello. – Stéphane Chazelas Sep 23 '22 at 15:25
  • awk's system("code") invokes sh -c code, so you might as well do system(cmds) here, or sh -c "$cmds" as awk is pointless or eval "$cmds" for the current shell to evaluate that code. – Stéphane Chazelas Sep 23 '22 at 15:27
  • Also beware that awk's -v mangles backslashes, and backslashes are common in shell code, arbitrary data should be passed via ENVIRON[] or ARGV[], not -v – Stéphane Chazelas Sep 23 '22 at 15:28
  • Still better not to store commands in a variable in the first place. That's what a function is for – Chris Davies Sep 23 '22 at 16:44