I have a Bash script on server A that finds the logged in SSH user via the logname
command, even if it's run as root
with sudo
. If I SSH into server A from my desktop and run the script, it works fine.
However, I've set up a post-commit hook on SVN server S which SSH's into A and runs the script there, which causes logname to fail, with error "logname: no login name".
If I SSH into S from my desktop, then SSH into A from there, it works correctly, so the error must be in the fact that the SVN hook ultimately does not run from a virtual terminal.
What alternative to logname
can I use here?
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 )
fi
echo $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)
fi
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With