Contents
How can we run a command stored in a variable?
The two better ways to store a command are a) use a function instead, b) use an array variable (or the positional parameters). Simply declare a function with the command inside, and run the function as if it were a command.
How to run bash script as a command?
~$ help eval eval: eval [arg …] Execute arguments as a shell command. Combine ARGs into a single string, use the result as input to the shell, and execute the resulting commands. Exit Status: Returns exit status of command or success if command is null.
What are the arguments in a bash script?
Bash supports a concept called “Positional Parameters”. These positional parameters represent arguments that are specified on the command line when a Bash script is invoked.
When to use Eval on multiple variables in Bash?
In the case where you have multiple variables containing the arguments for a command you’re running, and not just a single string, you should not use eval directly, as it will fail in the following case: Note that even though “Some arg” was passed as a single argument, eval read it as two.
Which is the safest way to run a command?
The safest way to run a (non-trivial) command is eval. Then you can write the command as you would do on the command line and it is executed exactly as if you had just entered it. But you have to quote everything.
How to store a variable in a shell script?
One way of dealing with complex cases is by using eval. There are other similar alternatives, like echo -ing the content of the variable and piping it to a shell input. All of them have the same problem. eval expands its arguments, and then, the bash interpreter will execute them.
Can a function be stored in a variable?
With functions or arrays, there is no such problem since the words are kept separate for the whole time, and there’s no quote or other processing for the contents of filename. Pretty much the only reason to use eval is one where the varying part involves shell syntax elements that can’t be brought in via variables (pipelines, redirections, etc.).
How to store a command in an array?
We can use an array to store a single command and its parameters. We set the first element with the program’s name, and then each parameter in subsequent array positions: Then, we can execute the command by expanding all the elements of the array: Note that we should use quotes around the array to correctly handle whitespace.