Bash – Change in bash prompt depending on whether first character is a space

bashpromptreadline

Right now every command which starts with a space character gets ignored by bash history (HISTCONTROL=ignoreboth in ~/.bashrc).
I would like to have a better visual cue when I press space as the first character in the prompt input field.

So is there a method of adding such a thing in the bash prompt?
For example, you would color a part of the prompt when it notices that you press space as the first character of the input field (because obviously reacting to other space characters in the input field would be silly).

Best Answer

So, admittedly, this is a little hackish but I think it will accomplish your end goal (even if it's not in the way you wanted). In your .bashrc (or anywhere else that gets sourced on login) add something similar to the following.

check_space() {
    if [[ "$READLINE_LINE" == " " ]]; then
        echo "This command will not be recorded in .bash_history!!"
    fi
    READLINE_LINE="$READLINE_LINE "
    READLINE_POINT=$(($READLINE_POINT+1))
}
bind -x '" ": check_space'

Every time the space bar is pressed it will call the check_space function to see whether it should print out a warning or not.

Thanks to help from Jeff here who got help from Dmitry here

EDIT FOR dlsso:

To use an arbitrary char instead of space:

check_char() {
    char=$1;
    if [[ "$READLINE_LINE" == "$char" ]]; then
        echo "This command will not be recorded in .bash_history!!"
    fi
    READLINE_LINE="$READLINE_LINE$char"
    READLINE_POINT=$(($READLINE_POINT+${#char}))
}
for char in {a..z}; do
    bind -x '"$char": check_char $char'
done
Related Question