How to run a command after assigning it to some variable in shell scripting? example: command_name=echo
Now, is there a way to use "$command_name hello world" instead of "echo hello world" ?
Yes. That exact code ($command_name hello world
) will work.
Make sure that quotes, if present, are placed only around the command name and each individual argument. If quotes are placed around the entire string, it will interpret the entire string as the command name, which isn't what you want.
For example:
command_name="echo"
$command_name hello world
will be interpreted as:
echo hello world
(which works), whereas:
command_name="echo"
"$command_name hello world"
is interpreted as:
"echo hello world"
which doesn't work because it's trying to find a command called echo hello world
rather than interpreting hello and world as arguments.
Similarly,
command_name="echo hello world"
"$command_name"
fails for the same reason, whereas:
command_name="echo hello world"
$command_name
works.
#!/bin/bash
var="command"
"$var"
worked for me in script file
You can use eval
for this:
Suppose you have an input_file
that has the following:
a b c d e f g
Now try in your terminal:
# this sed command coalesces white spaces
text='sed "s/ \+/ /g" input_file'
echo $text
sed "s/ \+/ /g" input_file
eval $text
a b c d e f g
With bash
arrays (which is the best practice when you have arguments):
commandline=( "echo" "Hello world" )
"${commandline[@]}"