Skip to content

Instantly share code, notes, and snippets.

@joshgachnang
Last active April 30, 2024 03:34
Show Gist options
  • Save joshgachnang/2306795 to your computer and use it in GitHub Desktop.
Save joshgachnang/2306795 to your computer and use it in GitHub Desktop.
Bash Check Username of User Running Script
if [ "$(whoami)" != "username" ]; then
echo "Script must be run as user: username"
exit 255
fi
@MrLoyal
Copy link

MrLoyal commented Jan 18, 2018

Thanks!

@TomAdam
Copy link

TomAdam commented Feb 28, 2018

This came first on a search so I think despite the age it is worth noting that exit only accepts values 0-255. Any out of range values will be changed to 255. See here: https://www.tldp.org/LDP/abs/html/exitcodes.html

@HaoZeke
Copy link

HaoZeke commented Oct 12, 2018

Couldn't you also just check $USER? That's faster than running $(whoami)..

if [ $USER != "username" ]; then
        echo "Script must be run as user: username"
        exit -1
fi

@palto42
Copy link

palto42 commented Jul 5, 2019

@HaoZeke
checking $USER is not working if the script is run with "sudo -u someuser", but whoami works correctly.

@dvodop
Copy link

dvodop commented Oct 4, 2019

@HaoZeke
checking $USER is not working if the script is run with "sudo -u someuser", but whoami works correctly.

it works fine

[cade@db01 tmp]$ sudo /tmp/test.sh
Current user: [root]
[cade@db01 tmp]$ sudo -i /tmp/test.sh
Current user: [root]
[cade@db01 tmp]$ sudo -i -u oracle /tmp/test.sh
Current user: [oracle]
[cade@db01 tmp]$ sudo -u oracle /tmp/test.sh
Current user: [oracle]
[cade@db01 tmp]$ sudo -u grid /tmp/test.sh
Current user: [grid]
[cade@db01 tmp]$ sudo -i -u grid /tmp/test.sh
Current user: [grid]
[cade@db01 tmp]$ cat /tmp/test.sh
#!/usr/bin/env bash
echo "Current user: [$USER]"
exit

@arendina
Copy link

arendina commented Apr 7, 2020

USER is set by the environment.
For example if you run bash in a clean environment (env -i bash) USER is not set.
If you are not sure about the environment is better to use whoami.

@MynaITLabs
Copy link

NOte, one of the sublt things with sudo and looking at environment variables in one line.

(root) $ sudo -u someuser echo ${USER}
root

Will always return 'root' since it ${USER} is value substituted before the call to sudo.

However, if you escape the $ symbol and pass the statement instead of value.
(root) $ sudo -u someuser bash -c "echo \${USER}"
someuser

Will more likely return what you intended.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment