In bash, from inside PROMPT_COMMAND, is there a way to tell if the user just hit 'return' and didn't enter a command?
Check If Last Command Was Empty in PROMPT_COMMAND
bashprompt
Related Solutions
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 $''
.).
From man bash
under CONDITIONAL EXPRESSIONS:
-t fd
True if file descriptor fd is open and refers to a terminal.
Assuming fd 1 is standard out, if [ -t 1 ]; then
should work for you. The Advanced Shell Scripting Guide claims that -t
used this way will fail over ssh
, and that the test (using stdin, not stdout) should therefore be:
if [[ -t 0 || -p /dev/stdin ]]
-p
tests if a file exists and is a named pipe. However, I'd note experientially this is not true for me: -p /dev/stdin
fails for both normal terminals and ssh sessions whereas if [ -t 0 ]
(or -t 1
) works in both cases (see also Gilles comments below about issues in that section of the Advanced Shell Scripting Guide).
If the primary issue is a specialized context from which you wish to call the script to behave in a way appropriate to that context, you can sidestep all these technicalities and save your self some fuss by using a wrapper and a custom variable:
!#/bin/bash
export SPECIAL_CONTEXT=1
/path/to/real/script.sh
Call this live_script.sh
or whatever and double click that instead. You could of course accomplish the same thing with command line arguments, but a wrapper would still be needed to make point and click in a GUI file browser work.
Best Answer
Check whether the history number was incremented. A cancelled prompt or a prompt where the user just pressed Enter won't increment the history number.
The history number is available in the variable
HISTCMD
, but this is not available inPROMPT_COMMAND
(because what you want there is in fact the history number of the previous command; the command that executesPROMPT_COMMAND
itself has no history number). You can get the number from the output offc
.Note that if you've turned on squashing of duplicates in the history (
HISTCONTROL=ignoredups
orHISTCONTROL=erasedups
), this will mistakenly report an empty command after running two identical commands successively.