execute multiple commands assigned to a single variable - bash
-
Hi, 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 result:
command: id ; date
-bash: id ; date : command not foundbut if I type a single command, it works. Thanks for your help
-
Hi, 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 result:
command: id ; date
-bash: id ; date : command not foundbut if I type a single command, it works. Thanks for your help
When the user types in
id; date
, that's the value of the $cmd variable. So when you want to execute the command, its as if you had typed"id; date"
at the command line, including the quote marks. So the bash interpreter is looking for a command namedid; date
. Its not treating this as "subscript" to be parsed and executed. For that you'll need to useeval
[k5054@localhost ~]$ cmd="id; date"
[k5054@localhost ~]$ $cmd
-bash: id;: command not found
[k5054@localhost ~]$ eval $cmd
uid=1002(k5054) gid=1002(k5054) groups=1002(k5054)
Mon 17 Oct 2022 02:37:19 PM UTC
[k5054@localhost ~]$Keep Calm and Carry On
-
When the user types in
id; date
, that's the value of the $cmd variable. So when you want to execute the command, its as if you had typed"id; date"
at the command line, including the quote marks. So the bash interpreter is looking for a command namedid; date
. Its not treating this as "subscript" to be parsed and executed. For that you'll need to useeval
[k5054@localhost ~]$ cmd="id; date"
[k5054@localhost ~]$ $cmd
-bash: id;: command not found
[k5054@localhost ~]$ eval $cmd
uid=1002(k5054) gid=1002(k5054) groups=1002(k5054)
Mon 17 Oct 2022 02:37:19 PM UTC
[k5054@localhost ~]$Keep Calm and Carry On