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?

  • 1
    You know you can re-run them like this, !219, right? – slm Jan 20 '14 at 15:13

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"
| 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\}//'`
| 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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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