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

Nathan Pk
  • 639
  • 4
  • 18
  • 25

5 Answers5

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.

AGWA
  • 266
  • 1
  • 3
1

command_name='echo'

$command_name "Hello World"

Addict
  • 693
  • 2
  • 7
  • 16
0
#!/bin/bash
var="command"
"$var"

worked for me in script file

jaudette
  • 2,275
  • 1
  • 16
  • 20
  • the substitution works in my case too. But when I tried to add arguments , it displays an error ("command not found") – Nathan Pk Nov 21 '12 at 19:33
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
sampson-chen
  • 40,497
  • 12
  • 76
  • 76
0

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

commandline=( "echo" "Hello world" )
"${commandline[@]}"
gniourf_gniourf
  • 38,851
  • 8
  • 82
  • 94