0

I would like to ask the user to enter a command that will be executed, but I don't understand why I can't assign two commands to the same variable.

Here is the code:

user@localhost:~# read -ep "command: " cmd ; "$cmd"

and the result:

command: id ; date
-bash: id ; date : command not found

but if I type a single command, it works.

Thanks for your help

raphael
  • 1
  • 1
  • try wrapping the commands in double quotes, e.g. `command: "id ; date"`. – bert Oct 17 '22 at 07:28
  • 3
    Storing commands in variables doesn't work very well. See [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) and ["How can I store a command in a variable in a shell script?"](https://stackoverflow.com/questions/5615717/how-can-i-store-a-command-in-a-variable-in-a-shell-script) – Gordon Davisson Oct 17 '22 at 07:33
  • The shell interprets the "$cmd" as a single word command in this context. Since no command exists with the name `id ; date` it prints out a "command not found" message. As an important aside note; running directly user-supplied input (without validating it) is a dangerous business. Your code could be "fixed" by replacing `"$cmd"` with `eval "$cmd"`, but this is still dangerous and may not work at all with complex commands. – M. Nejat Aydin Oct 17 '22 at 09:15
  • try this one: read -ep "command: " cmd ; bash -c "$cmd" – fflores Oct 17 '22 at 09:19

0 Answers0