Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How do I use the "history" command to fire the last run command?

share|improve this question
    
the up arrow key does the work for me. –  alfasin Oct 22 '12 at 0:49
add comment

migrated from stackoverflow.com Oct 15 '10 at 3:44

This question came from our site for professional and enthusiast programmers.

3 Answers

up vote 8 down vote accepted

You wouldn't. You'd use !!.

share|improve this answer
    
Provided that histexpand feature is on. set -o histexpand to turn it on, set +o histexpand to turn it off. –  Benoit Oct 14 '10 at 11:17
add comment

As Ignacio said, use !!, but if you insist:

$(history | sed '$d' | sed -n '$p' | cut -d ' ' -f 3-)

Explanation:

  • $() executes the output of the command inside
  • sed '$d' deletes the last command, i.e. 2001 $(history | sed '$d' | sed -n '$p' | cut -d ' ' -f 3-)
  • sed -n '$p' prints only the last line, i.e. 2000 yourpreviouscommand
  • cut -d ' ' -f 3- removes the first three fields, separated by spaces, i.e. <space>2000<space>

I think it can be made more concise and robust, but it works for now.

Edit: If you want to use history instead of !! because the shell you're using doesn't have !!, you're out of luck; history is a shell built-in, not a program. And simple shells are not likely to have it if they don't have !!. For example, dash doesn't:

imgx64@home:~$ dash
$ history
dash: history: not found
$ 
share|improve this answer
1  
Deeply evil. Very nice. –  dmckee Oct 15 '10 at 2:00
add comment

In Bash, the fc command may do what you're looking for.

From man bash:

...
In the second form, command is re-executed after each instance of pat is replaced by rep. A useful alias to use with this is r="fc -s", so that typing r cc runs the last command beginning with cc and typing r re-executes the last command.
...

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.