6

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).

  • 1
    Probably not: bash writes its prompt before you start typing, and does not update the prompt. – Thomas Dickey Oct 27 '15 at 8:43
  • I guess some bind magic can take you there. Adding readline tag. – Arthur2e5 Oct 28 '15 at 5:26
  • 2
    @ThomasDickey Readline 7.0 is able to change the prompt based on which mode your readline vi-mode is in, so this statement is not true. But, well, a general-purpose RL command for changing a prompt still doesn't exist. – Arthur2e5 Oct 29 '15 at 19:11
2

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
  • Note: does not work for bash 3.x (RIP Mac users). – dlsso May 19 '17 at 22:24
  • What would the syntax be if you wanted to use a variable instead of " "? I tried "$char", "${char}", "$(char)" but none seem to work. – dlsso May 19 '17 at 22:40
  • How and where are you trying to set the variable? $char and ${char} should both work if set appropriately. – David King May 22 '17 at 12:28
  • for char in {a..z} so perhaps it's not the same as a normal variable. echo $char works as expected in that case though, so I expected the binding to work as well. – dlsso May 23 '17 at 14:39
  • @dlsso Check my edit – David King May 24 '17 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.