Zaico
Zaico

Reputation: 31

How to use output directly as a command

with this grep it shows a comand I used:

echo `history | grep "ssh root" | head -1| cut -c6-`

with this output:

ssh [email protected]

I want the output to directly execute as the command instead of printed. How can I do it?

Upvotes: 0

Views: 82

Answers (3)

tk421
tk421

Reputation: 5947

Use eval.

$ eval `history | grep "ssh root" | head -1| cut -c6-`

From eval command in Bash and its typical uses:

eval takes a string as its argument, and evaluates it as if you'd typed that string on a command line.

And the Bash Manual (https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#Bourne-Shell-Builtins)

eval

  eval [arguments]

The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of eval. If there are no arguments or only empty arguments, the return status is zero.

Upvotes: 0

Oliver I
Oliver I

Reputation: 456

Ideally you'd be using the $(cmd) syntax rather than the `cmd` syntax. This makes it easier to nest subshells as well as keep track of what's going on.

That aside, if you remove the echo statement it will run the script:

# Prints out ls
echo $( echo ls )

# Runs the ls command
$( echo ls )

Upvotes: 1

Thomas Kühn
Thomas Kühn

Reputation: 9810

In principle, this can be done by using the $() format, so

$(history | grep "ssh root" | head -1| cut -c6-)

should do what you ask for. However, I don't think that it is advisable to do so, as this will automatically execute the command that results from your grep, so if you did a mistake, a lot of bad things can happen. Instead I suggest reviewing your result before re-executing. bash history has a lot of nice shortcuts to deal with these kind of things. As an example, imagine:

> history | grep "ssh root"
  756  ssh [email protected]

you can call this command on line 756 easily by typing

!756

It's definitely much safer. Hope this helps.

Upvotes: 3

Related Questions