Daniel
Daniel

Reputation: 12016

.bashrc : how to check in what terminal the shell is running

I have the following in my .bashrc:

bind '"\e[A"':history-search-backward
bind '"\e[B"':history-search-forward

However, when I call shell from within Emacs, I get the following message:

bash: bind: warning: line editing not enabled

bash: bind: warning: line editing not enabled

And as a consequence my prompt gets messed up.

How can I detect (from within my .bashrc), that my shell is being called from emacs or, alternatively, not from a standard terminal?

My goal is to wrap the calls to bind so that they are only executed in a proper terminal.

Upvotes: 3

Views: 1982

Answers (3)

Alex Vorobiev
Alex Vorobiev

Reputation: 4359

This snippet specifically tests if line editing is enabled in bash or not. It works everywhere, not just in the emacs shell:

if [[ "$(set -o | grep 'emacs\|\bvi\b' | cut -f2 | tr '\n' ':')" != 'off:off:' ]]; then
  echo "line editing is on"
fi

It could probably be simplified...

Upvotes: 1

Daniel
Daniel

Reputation: 12016

Probing for a variable called EMACS didn't work for me under Emacs 25 and bash 4.2.

However, looking for differences in the environment of the shell within and outside of Emacs I found a variable called INSIDE_EMACS only set when running from Emacs.

The solution that worked for me is therefore:

if [[ ! -v INSIDE_EMACS ]]; then
    bind '"\e[A"':history-search-backward
    bind '"\e[B"':history-search-forward
fi

Echoing INSIDE_EMACS returns the Emacs release number.

Upvotes: 3

chepner
chepner

Reputation: 530823

bash disables line editing because when it sees a variable named EMACS in its environment. You can use the same variable to conditionally create those bindings:

if [[ ! -v EMACS ]]; then
    bind '"\e[A"':history-search-backward
    bind '"\e[B"':history-search-forward
fi

Upvotes: 2

Related Questions