I am trying to execute a shell script like below
cmds=('uptime' 'free -m' 'nproc')
for cmd in ${cmds[@]};
do
echo $($cmd)
done
Execution is breaking when it comes to free -m
execution because of space.
vagrant@vagrant-ubuntu-trusty-64:~$ bash for_my_script.sh
03:42:50 up 56 min, 1 user, load average: 0.00, 0.00, 0.00
total used free shared buff/cache available
Mem: 499928 108516 43204 1844 348208 366140
Swap: 0 0 0
for_my_script.sh: line 5: -m: command not found
1
vagrant@vagrant-ubuntu-trusty-64:~$
I tried iterating with for by storing commands in variable
vagrant@vagrant-ubuntu-trusty-64:~$ cmds="uptime,free -m"
vagrant@vagrant-ubuntu-trusty-64:~$ for cmd in "${cmds//,/ }"; do echo "$($cmd)"; done
uptime: invalid option -- 'm'
vagrant@vagrant-ubuntu-trusty-64:~$ cmds="uptime,'free -m'"
vagrant@vagrant-ubuntu-trusty-64:~$ for cmd in "${cmds//,/ }"; do echo "$($cmd)"; done
uptime: invalid option -- 'm'
With no success.
is touching IFS
is the only way for this type of problem?
any inputs are much appreciated.
Thank you.
CodePudding user response:
You have to change your code from:
cmds=('uptime' 'free -m' 'nproc')
for cmd in ${cmds[@]};
do
echo $(${cmd})
done
into
cmds=('uptime' 'free -m' 'nproc')
for cmd in "${cmds[@]}";
do
echo $(${cmd})
done
You missed double quotes around ${cmds[@]}
.