Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
1  
You know you can re-run them like this, !219, right? –  slm Jan 20 at 15:13
    
Thank you. I didn't know that –  Loom Jan 20 at 15:27

3 Answers 3

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"
hello
$ history | grep hello
 5057  echo "hello"
$ !5057
echo "hello"
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
  NTH=$1
  shift
  history \
  | grep -v "nthhist" \
  | grep "$@" \
  | head -${NTH} | tail -1 \
  | while read id cmd
  do
    $cmd
  done
}
share|improve this answer

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.