Get SSH login name in bash script Get SSH login name in bash script bash bash

Get SSH login name in bash script


You could use the id command:

  $ ssh 192.168.0.227 logname  logname: no login name

However

  $ ssh 192.168.0.227 id  uid=502(username) gid=100(users) groups=100(users)

In a bash script you can cut the username out of the id output with something like

  $ id | cut -d "(" -f 2 | cut -d ")" -f1  username

To have a script that works both in a sudo environment and without a terminal you could always execute different commands conditionally.

if logname &> /dev/null ; then     NAME=$( logname )else     NAME=$( id | cut -d "(" -f 2 | cut -d ")" -f1 )fiecho $NAME


This is what I ended up with.

if logname &> /dev/null; then    human_user=$(logname)else    if [ -n "$SUDO_USER" ]; then        human_user=$SUDO_USER    else        human_user=$(whoami)    fifi


Use id -nu. No silly forking and cutting to get at the user name.