Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh run a command stored in a variable?

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
like image 638
D.C. Avatar asked Dec 02 '12 00:12

D.C.


People also ask

How can we run a command stored in a variable?

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.

How do I run a command in a bash variable?

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.

How do you call a variable in a shell script?

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.


1 Answers

Use eval:

eval ${install_cmd}
like image 55
qqx Avatar answered Nov 15 '22 23:11

qqx