2

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" ?

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

command_name='echo'

$command_name "Hello World"

Comments

0
#!/bin/bash
var="command"
"$var"

worked for me in script file

1 Comment

the substitution works in my case too. But when I tried to add arguments , it displays an error ("command not found")
0

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

1 Comment

Avoid eval whenever and wherever possible -- it has a well-deserved reputation for causing bugs.
0

With bash arrays (which is the best practice when you have arguments):

commandline=( "echo" "Hello world" )
"${commandline[@]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.