Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute a command stored in a variable?

What is the correct way to call some command stored in variable?

Are there any differences between 1 and 2?

#!/bin/sh cmd="ls -la $APPROOTDIR | grep exception"  #1 $cmd  #2 eval "$cmd" 
like image 455
Volodymyr Bezuglyy Avatar asked Jan 12 '11 12:01

Volodymyr Bezuglyy


People also ask

How do you execute a command 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 you store a command in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do I run a command inside Echo?

To write a simple string of text to the terminal window, type echo and the string you want it to display: echo My name is Dave. The text is repeated for us.


2 Answers

Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the Bash man page):

  • initial word splitting
  • brace expansion
  • tilde expansion
  • parameter, variable and arithmetic expansion
  • command substitution
  • secondary word splitting
  • path expansion (aka globbing)
  • quote removal

Using $cmd directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.

Using eval "$cmd" does nothing until the quote removal phase, where $cmd is returned as is, and passed as a parameter to eval, whose function is to run the whole chain again before executing.

So basically, they're the same in most cases and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:

$ cmd="echo foo{bar,baz}"  $ $cmd foo{bar,baz}  $ eval "$cmd" foobar foobaz 
like image 95
JB. Avatar answered Sep 24 '22 09:09

JB.


If you just do eval $cmd when we do cmd="ls -l" (interactively and in a script), you get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd will generate a "command not found" (or some such) message.

So try use to eval (near "The args are read and concatenated together") and use a finished command, not one that generates an error message.

like image 28
Henno Brandsma Avatar answered Sep 26 '22 09:09

Henno Brandsma