In a bash-script I'd like to retrieve the last command which was executed. In bash itself the following command works like a charm.
lastCommand=$(echo `history |tail -n2 |head -n1` | sed 's/[0-9]* //')
Inside scripts however history doesn't work at all.
Is there a way to retrieve the command inside a script?
2 Answers 2
For bash v4+ :
Use interactive mode in shell.
Set she-bang as
#!/bin/bash -i
and history inside of your script will work.
$ cat test.sh
#!/bin/bash
history | wc -l
$ ./test.sh
0
$ sed -i '1s/bash/bash -i/' test.sh
$ ./test.sh
6495
Commands was executed inside of script are not recorded into history.
For bash v3 (and possible for older ones)
The way above doesn't work for this vesions of bash. However you can remove she-bang at all and history will work well. This way also works great for bash v4.
set she-bang as interactive and do not forget about
set -o historylike chepner mentioned.
#!/bin/bash -i
set -o history
PS. history |tail -n2 |head -n1 doesn't equal to the last command. it is command before last one.
Note if last or prelast commands were multiline it won't return the correct result.
btw in console you can use !-2 to refer to prelast command instead of your strange construction. unfortunately it seems doesn't work in shell script even in interactive mode.
-
History still doesn't work even when setting the shell to #!/bin/bash -i, maybe it is because the script is started via Ant?Hedge– Hedge2012年07月25日 12:45:12 +00:00Commented Jul 25, 2012 at 12:45
-
I've added simple exapmle to my answer. It should work at your side. Please try it. May be the trouble is in commands after history?rush– rush2012年07月25日 12:49:33 +00:00Commented Jul 25, 2012 at 12:49
-
I've got GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin11), I tried a simple history without arguments as well and it doesn't work.Hedge– Hedge2012年07月25日 12:55:26 +00:00Commented Jul 25, 2012 at 12:55
-
wow. in bash v3 (and v4 too) you can just remove the she-bang at all and history will work pretty well.rush– rush2012年07月25日 13:05:04 +00:00Commented Jul 25, 2012 at 13:05
-
History expansion is just one feature enabled by default in an interactive shell. Rather than use
-i, just useset -o historyto specifically turn on history expansion in your script.chepner– chepner2012年07月25日 13:14:09 +00:00Commented Jul 25, 2012 at 13:14
Does this help?
lastCommand=$(`cat ~/.bash_history |tail -n2 |head -n1` | sed 's/[0-9]* //')
Or maybe this:
echo !!
As bash have a build in facilities to provide last command
-
5
!!equal to the last command. However OP construction equals to the command just before the last one.!-2exactly equals to OP construction. Unfortunately both!!and!-2don't work inside of shell script.rush– rush2012年07月25日 12:42:35 +00:00Commented Jul 25, 2012 at 12:42