Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you tell if bash is being accessed from a remote machine?

Tags:

bash

I am trying to write out a dynamic bash profile for a few machines, and was wondering if there is a variable that allows .bashrc if it is being accessed remotely. I've seen a few examples using X variables, but that is irrelevant to both machines.

like image 319
Kyle Hotchkiss Avatar asked Aug 13 '11 16:08

Kyle Hotchkiss


2 Answers

if [ "$SSH_CONNECTION" ]; then
  echo I am remote
else
  echo I am local
fi
like image 103
DigitalRoss Avatar answered Nov 15 '22 07:11

DigitalRoss


When you connect via ssh, your bash process is a child of sshd ($PPID is a variable of bash's parent process - ssh that is, if you connect remotely). You can check for that:

if ps ax | grep ^$PPID'.*sshd' &> /dev/null; then  
  # do your stuff
fi

Edit: I was bored and used time to get execution times and found out that this version apparently is a couple of milliseconds faster:

if grep ^sshd: /proc/$PPID/cmdline &> /dev/null; then
  # do your stuff
fi
like image 37
keks Avatar answered Nov 15 '22 05:11

keks