Bash: Test Who Runs a Script: Difference between revisions
From WikiMLT
m Стадий: 6 [Фаза:Утвърждаване, Статус:Утвърден]; Категория:Linux Server |
m Text replacement - "mlw-continue" to "code-continue" |
||
(One intermediate revision by the same user not shown) | |||
Line 5: | Line 5: | ||
cat test-user.sh | cat test-user.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="bash" line="1" class=" | <syntaxhighlight lang="bash" line="1" class="code-continue"> | ||
#!/bin/bash | #!/bin/bash | ||
SCRIPT_UID="33" | SCRIPT_UID="33" | ||
Line 14: | Line 14: | ||
echo "The script is running as $(id $EUID -un)." | echo "The script is running as $(id $EUID -un)." | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="shell" line="1" class=" | <syntaxhighlight lang="shell" line="1" class="code-continue"> | ||
./test-user.sh | ./test-user.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="shell-session" class=" | <syntaxhighlight lang="shell-session" class="code-continue"> | ||
Please run as www-data, use: sudo -u www-data ./test-user.sh | Please run as www-data, use: sudo -u www-data ./test-user.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="shell" line="1" class=" | <syntaxhighlight lang="shell" line="1" class="code-continue"> | ||
./test-user.sh | ./test-user.sh | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="shell-session" class=" | <syntaxhighlight lang="shell-session" class="code-continue"> | ||
The script is running as www-data. | The script is running as www-data. | ||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 07:29, 26 September 2022
Solution
cat test-user.sh
#!/bin/bash
SCRIPT_UID="33"
[[ $EUID -ne $SCRIPT_UID ]] && {
echo "Please run as $(id $SCRIPT_UID -un), use: sudo -u $(id $SCRIPT_UID -un) $0"
exit 1
}
echo "The script is running as $(id $EUID -un)."
./test-user.sh
Please run as www-data, use: sudo -u www-data ./test-user.sh
./test-user.sh
The script is running as www-data.
References
- Ask Ubuntu: How do I find which user executes the script when is used sudo?
- Stack Overflow: Difference between EUID and UID?
- Unix & Linux: How do I change $EUID value to non-zero in the bash shell?