Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

For example, I have the following output from command:

loom@loom:$ history | grep MAKE
  219  ../build.sh -DCMAKE_BUILD_TYPE=Debug ..
  909  history | grep MAKE

How to write a command, that start the first command from the list? Also, I'd like to know how to start n-th command from output of history | grep something?

share|improve this question
You know you can re-run them like this, !219, right? – slm Jan 20 '14 at 15:13
Thank you. I didn't know that – Loom Jan 20 '14 at 15:27
up vote 2 down vote accepted

See those numbers on the left of the output? You can use them to refer to that command with shell history expansion; ![number] in most shells.

This works both in bash and zsh:

$ echo "hello"
$ history | grep hello
 5057  echo "hello"
$ !5057
echo "hello"
share|improve this answer

Not a very elegant solution but works.

i=5  # Execute 5th command from the beginning of history
`history | sed -n "${i}p" | sed 's/^.\{7\}//'`
share|improve this answer

the following little bash-function should do what you want in many cases.

usage: nthhist 3 MAKE will run the 3rd command that contained MAKE.

note: this won't work if the command found this way is only a bash-internal

nthhist() {
  local NTH
  history \
  | grep -v "nthhist" \
  | grep "$@" \
  | head -${NTH} | tail -1 \
  | while read id cmd
share|improve this answer

Your Answer


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.