Bash – Printing (saving) the last bash input command

bashprompt

How can I get the last executed command from bash? I know that !!:p prints the last command, but it seems I can't use that anywhere except the bash prompt. I tried echo !!:p but it prints

~/Downloads$ pwd
Downloads
~/Downloads$ echo !!:p
echo pwd

I want to use this inside the PROMPT_COMMAND variable so I need to get it as a string so I can just print it out. Is there an easy way to do this? Am I looking in the wrong place?

I guess I'm not clear. I need to store the last command run so I can re-display it after the output and before the next prompt. For example this is what I want the output to look like:

~/Downloads$ pwd
Downloads

pwd
~/Downloads$

I'm doing this my changing my prompt in my .bashrc file

PROMPT_COMMAND='echo -en "\033[38;5;2m"!!:p"\033[0m\n"'
PS1='\W\$'

But !!:p only works correctly from the bash prompt. So how can I store the last command so that I can reprint it later?

Best Answer

You can access the just-executed command line with the history built-in. (I have no idea why history 1 prints the just-executed command line but fc -nl -1 prints the previous commmand, as does fc -nl 0.)

PROMPT_COMMAND='echo -en "\033[38;5;2m"; history 1; echo -en "\033[0m\n"'

This prints a number before the command text. Here's a version that removes the number. (It may be incorrect if you go beyond 99999 history lines, I don't know how bash formats the number then.)

prompt_function () {
  local prompt_history="$(history 1)"
  prompt_history=${prompt_history:7}
  echo -En $'\033[38;5;2m'"$prompt_history"$'\033[0m\n'
}
PROMPT_COMMAND=prompt_function

(Note that echo -en ..."$prompt_history"... would expand backslashes in the command line, so I use echo -E and let the shell expansion generate the control characters with $''.).

Related Question