In a shell script (in .zshrc) I am trying to execute a command that is stored as a string in another variable. Various sources on the web say this is possible, but I'm not getting the behavior i expect. Maybe it's the ~
at the beginning of the command, or maybe it's the use of sudo
, I'm not sure. Any ideas? Thanks
function update_install()
{
# builds up a command as a string...
local install_cmd="$(make_install_command $@)"
# At this point the command as a string looks like: "sudo ~some_server/bin/do_install arg1 arg2"
print "----------------------------------------------------------------------------"
print "Will update install"
print "With command: ${install_cmd}"
print "----------------------------------------------------------------------------"
echo "trying backticks"
`${install_cmd}`
echo "Trying \$()"
$(${install_cmd})
echo "Trying \$="
$=install_cmd
}
Output:
Will update install
With command: sudo ~some_server/bin/do_install arg1 arg2
trying backticks
update_install:9: no such file or directory: sudo ~some_server/bin/do_install arg1 arg2
Trying $()
update_install:11: no such file or directory: sudo ~some_server/bin/do_install arg1 arg2
Trying $=
sudo ~some_server/bin/do_install arg1 arg2: command not found
Here, the first line of the script i.e. “#!/bin/bash” shows that this file is in fact a Bash file. Then we have created a variable named “test” and have assigned it the value “$(echo “Hi there!”)”. Whenever you want to store the command in a variable, you have to type that command preceded by a “$” symbol.
Using variable from command line or terminal You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.
Note that there must be no spaces around the "=" sign: VAR=value works; VAR = value doesn't work. In the first case, the shell sees the "=" symbol and treats the command as a variable assignment. In the second case, the shell assumes that VAR must be the name of a command and tries to execute it.
Use eval
:
eval ${install_cmd}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With