Sometimes the output of some command include other commands. And I'd like to start that command from output without using a mouse. For example, when command is not installed there is a message with line for installing this command:
$ htop
The program 'htop' is currently not installed. You can install it by typing:
sudo apt-get install htop
So. There I'd like to type a command, that will start the command from last line from output of htop
. How it can be done?
Edit: I'll try show what I mean. There are two lines in "output" of command htop
(actually, it's an error message). Second line of this message is the command sudo apt-get install htop
. So I'd like to extract second line from output, and start it's like command itself. The following is a rubbish but it shows what I mean:
htop | tail -1 | xargs start_command
Best Answer
The right thing to do here is to set up bash to prompt for installation, as explained in SamK's answer. I'll answer strictly from a shell usage perspective.
First, the text you're trying to grab is on the command's standard error, but a pipe redirects the standard output, so you need to redirect stderr to stdout.
To use the output of a command as part of a command line, use command substitution.
The result of the command substitution is split into words and each word is interpreted as a wildcard pattern. Here this happens to do the right thing: this is a command line with words separated by spaces, and there are no wildcard characters.
To evaluate a string as a shell command, use
eval
. To treat the result of the command as a string rather than a list of wildcard patterns, put it in double quotes.Of course, before evaluating a shell command like that, make sure it's really what you want to execute.