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