0

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?

5
  • remove the echo? Commented May 19, 2017 at 15:27
  • Pipe it to sh or bash? Commented May 19, 2017 at 15:41
  • @123 leaving out the echo does not work. Commented May 19, 2017 at 15:41
  • @ThomasKühn yes it would. Commented May 19, 2017 at 15:52
  • @123 my apologies, I mistook the `` around the command for this: ''. Commented May 19, 2017 at 15:54

3 Answers 3

3

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.

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

Comments

1

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 )

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.