Re: a 'who called me?' variable?
Dan Berdine wrote:
> Is there an environment variable in bash that can be used to tell where
> bash is running from? For example, is there a variable I can test in
> my .bashrc to tell whether I am running remotly, from a tty, from
> konsole, an xterm, etc.? I'v looked at the Advanced Scripting HOWTO,
> but the only thing that looked promising was "$BASH_ENV" which seems to
> be empty.
I use the following script, which determines the appropriate value for
the DISPLAY variable (for the benefit of X apps) appropriately according
to how I'm accessing the system. It probably isn't perfect (I'm sure if
you have two monitors, it may screw up, or if you're on a graphics
terminal connected by a serial line, or some other unusual connection),
but it works for me.
--- cut here ---
# by Craig Dickson
# This script determines a good value for the DISPLAY variable, and echos
# it to stdout.
# Note that the SSH_CLIENT shell variable is not normally exported, and
# therefore will not be available in a subshell. Also, the PPID variable
# will be different in a subshell. Because of these facts, it is best to
# source this script, as in "export DISPLAY=$(source getdisp)".
# If you are logged in via ssh, then the SSH_CLIENT variable will contain,
# among other things, your remote IP.
if [ -n "$SSH_CLIENT" ]; then
echo "getdisp: display determined by SSH_CLIENT." >&2
disp=$(echo $SSH_CLIENT | cut -d " " -f 1):0.0
# Otherwise, if you are in some sort of xterm session (including rxvt or
# gnome-terminal), then the COLORTERM variable will be set, or TERM=xterm,
# and netstat can be used together with the PPID variable to find your
# remote IP. Interestingly, this also works if your xterm session is at
# the console, because there will be no network connection associated with
# your PPID, so your display will be correctly identified as :0.0 (as long
# as you have only one display...).
elif [ -n "$COLORTERM" -o "$TERM" = "xterm" ]; then
echo "getdisp: display determined by X terminal PPID." >&2
disp=$(netstat -np --tcp 2>/dev/null | grep " $PPID/")
disp=$(echo $disp | cut -d " " -f 5 | cut -d ":" -f 1):0.0
# Otherwise, we try to use 'last' to figure out where you're connecting from.
# This has to be done in one of two forms. Neither is guaranteed to work.
# If both fail, nothing will be echoed.
disp=$(last -20ai | grep $USER | head -1 | cut -c 61-):0.0
if [ "$disp" = "0.0.0.0:0.0" ]; then
echo "getdisp: display determined by last -a." >&2
disp=$(last -20a | grep $USER | head -1 | cut -c 61-)
echo "getdisp: display determined by last -ai." >&2
if [ -n "$disp" ]; then
--- cut here ---