
- Question
- But Teo what that means?
- Recommendation
- How do you check what permissions a user has in Linux?
- How do I find my root username in Linux?
- What is root in terminal?
- Information related to the topic bash check if user is root
- Optimized all-round solution for performance and reliability; all shells compatible
- Benchmark (save to file is_user_root__benchmark)
- Portable pure POSIX solution + Example of usage of the above function
- See some more details on the topic bash check if user is root here
- How do I check if I have root access? – Unix Stack Exchange
- Check the bash shell script is being run by root or not – nixCraft
- Check if user is root/sudo before running a script – The Electric …
- How do I check if a user has root access in Linux? – OS Today
- Explanation
- Объяснение
- How do I access root?
- How do I know if user is root or sudo?
- Bash script to check if a specific user is present in etc passwd
- Images related to the topicBash script to check if a specific user is present in etc passwd
- How do you find if a user has permissions on a particular file?
- How do you check user permissions in Unix?
- How do I give a user root access in Linux?
- Is a root user in Linux?
- Complete Shell Scripting | Run shell script with root user or with sudo privilage
- Images related to the topicComplete Shell Scripting | Run shell script with root user or with sudo privilage
- What does chmod 777 mean?
- How do I login as root in terminal?
- Why I post this solution after so many years the OP has asked
- What is the user ID of root?
- Shell Script Check If Directory Exists – Folder – Linux – BASH – tutorial
- Images related to the topicShell Script Check If Directory Exists – Folder – Linux – BASH – tutorial
- Заключение
- Conclusion
- Related Query
- More Query from same tag
- Почему я публикую это решение после стольких лет, когда ОП спросил
- Оптимизированное bash решение для производительности и надежности
- Портативное решение POSIX solution
Question
I’m working on a BASH script but I do not want to allow people to run the script as root for security measures. Does anyone know what’s the best way to stop the execution of the script if it is ran as root?
Submit an answer
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign In or Sign Up to Answer
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Get our biweekly newsletter
Sign up for Infrastructure as a Newsletter.
Hollie’s Hub for Good
Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.
Become a contributor
You get paid; we donate to tech nonprofits.
Get started for free
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
New accounts only. By submitting your email you agree to our Privacy Policy.
One strategy is to (safely!) split your PATH
variable into an array, and scan each entry. Splitting is done like so:
IFS=: read -r -d '' -a path_ary < <(printf '%s:\0' "$PATH")
See my mock which
and How to split a string on a delimiter answers.
With this command you’ll have a nice array path_ary
that contains each fields of PATH
.
You can then check whether there’s an empty field, or a .
field or a relative path in there:
for ((i=0;i<${#path_ary[@]};++i)); do
if [[ ${path_ary[i]} = ?(.) ]]; then
printf 'Warning: the entry %d contains the current dir\n' "$i"
elif [[ ${path_ary[i]} != /* ]]; then
printf 'Warning: the entry %s is not an absolute path\n' "$i"
fi
done
You can add more elif
‘s, e.g., to check whether the entry is not a valid directory:
elif [[ ! -d ${path_ary[i]} ]]; then
printf 'Warning: the entry %s is not a directory\n' "$i"
Now, to check for the permission and ownership, unfortunately, there are no pure Bash ways nor portable ways of proceeding. But parsing ls
is very likely not a good idea. stat
can work, but is known to have different behaviors on different platforms. So you’ll have to experiment with what works for you. Here’s an example that works with GNU stat
on Linux:
read perms owner_id < <(/usr/bin/stat -Lc '%a %u' -- "${path_ary[i]}")
You’ll want to check that owner_id
is 0
(note that it’s okay to have a dir path that is not owned by root; for example, I have /home/gniourf/bin
and that’s fine!). perms
is in octal and you can easily check for g+w
or o+w
with bit tests:
elif [[ $owner_id != 0 ]]; then
printf 'Warning: the entry %s is not owned by root\n' "$i"
elif ((0022&8#$perms)); then
printf 'Warning: the entry %s has group or other write permission\n' "$i"
Note the use of 8#$perms
to force Bash to understand perms
as an octal number.
else
# In the else statement, the corresponding entry is good
unset_it=false
fi
if $unset_it; then
printf 'Unsetting entry %s: %s\n' "$i" "${path_ary[i]}"
unset path_ary[i]
fi
of course, you’ll have unset_it=true
as the first instruction of the loop.
And to put everything back into PATH
:
IFS=: eval 'PATH="${path_ary[*]}"'
I know that some will cry out loud that eval
is evil, but this is a canonical (and safe!) way to join array elements in Bash (observe the single quotes).
Finally, the corresponding function could look like:
clean_path() {
local path_ary perms owner_id unset_it
IFS=: read -r -d '' -a path_ary < <(printf '%s:\0' "$PATH")
for ((i=0;i<${#path_ary[@]};++i)); do
unset_it=true
read perms owner_id < <(/usr/bin/stat -Lc '%a %u' -- "${path_ary[i]}" 2>/dev/null)
if [[ ${path_ary[i]} = ?(.) ]]; then
printf 'Warning: the entry %d contains the current dir\n' "$i"
elif [[ ${path_ary[i]} != /* ]]; then
printf 'Warning: the entry %s is not an absolute path\n' "$i"
elif [[ ! -d ${path_ary[i]} ]]; then
printf 'Warning: the entry %s is not a directory\n' "$i"
elif [[ $owner_id != 0 ]]; then
printf 'Warning: the entry %s is not owned by root\n' "$i"
elif ((0022 & 8#$perms)); then
printf 'Warning: the entry %s has group or other write permission\n' "$i"
else
# In the else statement, the corresponding entry is good
unset_it=false
fi
if $unset_it; then
printf 'Unsetting entry %s: %s\n' "$i" "${path_ary[i]}"
unset path_ary[i]
fi
done
IFS=: eval 'PATH="${path_ary[*]}"'
}
for ((oneblock=1;oneblock--;)); do
# This block is only executed once
# You can exit this block with break at any moment
done
clean_path() {
local path_ary perms owner_id unset_it oneblock
local -A lookup
IFS=: read -r -d '' -a path_ary < <(printf '%s:\0' "$PATH")
for ((i=0;i<${#path_ary[@]};++i)); do
unset_it=true
for ((oneblock=1;oneblock--;)); do
if [[ ${path_ary[i]} = ?(.) ]]; then
printf 'Warning: the entry %d contains the current dir\n' "$i"
break
elif [[ ${path_ary[i]} != /* ]]; then
printf 'Warning: the entry %s is not an absolute path\n' "$i"
break
elif [[ ! -d ${path_ary[i]} ]]; then
printf 'Warning: the entry %s is not a directory\n' "$i"
break
elif [[ ${lookup[${path_ary[i]}]} ]]; then
printf 'Warning: the entry %s appears multiple times\n' "$i"
break
fi
# Here I'm sure I'm dealing with a directory
read perms owner_id < <(/usr/bin/stat -Lc '%a %u' -- "${path_ary[i]}")
if [[ $owner_id != 0 ]]; then
printf 'Warning: the entry %s is not owned by root\n' "$i"
break
elif ((0022 & 8#$perms)); then
printf 'Warning: the entry %s has group or other write permission\n' "$i"
break
fi
# All tests passed, will keep it
lookup[${path_ary[i]}]=1
unset_it=false
done
if $unset_it; then
printf 'Unsetting entry %s: %s\n' "$i" "${path_ary[i]}"
unset path_ary[i]
fi
done
IFS=: eval 'PATH="${path_ary[*]}"'
}
All this is really safe regarding spaces and glob characters and newlines inside PATH
; the only thing I don’t really like is the use of the external (and non-portable) stat
command.
Я пишу script, который требует прав на уровне корневого уровня, и я хочу сделать так, чтобы, если script не запущен как root, он просто перекликается с “Пожалуйста, запустите от имени пользователя root”. и выходы.
Здесь некоторый псевдокод для того, что я ищу:
if (whoami != root)
then echo "Please run as root"
else (do stuff)
fi
exit
Как я могу (чище и безопасно) справиться с этим? Спасибо!
А, просто для того, чтобы уточнить: часть (сделайте что-то) будет включать в себя запуск команд, которые сами по себе требуют root. Так что запуск его, как обычный пользователь, просто придумал бы ошибку. Это просто предназначено для чистого запуска script, для которого требуются корневые команды, без использования sudo внутри script, я просто ищу какой-то синтаксический сахар.
Было дано несколько ответов, но, по-видимому, лучшим способом является использование:
-
id -u
- Если запустить с правами root, вернет идентификатор 0.
Это кажется более надежным, чем другие методы, и кажется, что он возвращает id из 0, даже если script выполняется через sudo
.
Переменная среды $ EUID содержит текущий UID пользователя. Root UID равен 0. Используйте что-то вроде этого в вашем скрипте:
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit
fi
В bash script у вас есть несколько способов проверить, является ли текущий пользователь root.
Как предупреждение , не проверяйте, является ли пользователь root, используя имя пользователя root
. Ничто не гарантирует, что пользователь с ID 0 называется root
. Это очень сильное соглашение, которое широко применяется, но любой может переименовать суперпользователя в другое имя.
Я думаю, что лучший способ использования bash – использовать $EUID
, с man-страницы:
EUID Expands to the effective user ID of the current user, initialized
at shell startup. This variable is readonly.
Это лучший способ, чем $UID
, который может быть изменен и не отражает реального пользователя, запускающего script.
if (( $EUID != 0 )); then
echo "Please run as root"
exit
fi
Способ, которым я подхожу к этой проблеме, заключается в том, чтобы вставлять sudo
в мои команды, когда он не запускается с правами root. Вот пример:
SUDO=''
if (( $EUID != 0 )); then
SUDO='sudo'
fi
$SUDO a_command
Таким образом моя команда запускается root при использовании суперпользователя или sudo
при запуске обычного пользователя.
Если ваш script всегда должен быть запущен root, просто установите права соответственно (0500
).
if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
if [[ `id -u` -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
Кроме того, при правильном использовании sudo
вы можете проверить script и посмотреть, работает ли он с правами root. Если нет, попросите его вспомнить через sudo
, а затем запустите с правами root.
В зависимости от того, что делает script, другой может быть настройка записи sudo
для любых специализированных команд, которые могут понадобиться script.
Существует простая проверка для пользователя, являющегося пользователем root.
error() {
printf '\E[31m'; echo "$@"; printf '\E[0m'
}
if [[ $EUID -eq 0 ]]; then
error "This script should not be run using sudo or as the root user"
exit 1
fi
Это также предполагает, что вы хотите выйти с 1, если вы терпите неудачу. Функция error
– это некоторое чутье, которое устанавливает выходной текст в красный (не нужен, но довольно классный, если вы меня спрашиваете).
0- Прочитайте официальную документацию GNU Linux, есть много способов сделать это правильно.
1- убедитесь, что вы помещаете подпись оболочки, чтобы избежать ошибок в интерпретации:
#!/bin/bash
2- это мой script
#!/bin/bash
if [[ $EUID > 0 ]]; then # we can compare directly with this syntax.
echo "Please run as root/sudo"
exit 1
else
#do your stuff
fi
Очень простой способ просто поставить:
if [ "$(whoami)" == "root" ] ; then
# you are root
else
# you are not root
fi
Преимущество использования этого вместо id
заключается в том, что вы можете проверить, не работает ли какой-либо пользователь, не являющийся пользователем root; например.
if [ "$(whoami)" == "john" ] ; then
# you are john
else
# you are not john
fi
Если script действительно требует доступа к корню, тогда его права на файлы должны отражать это. Наличие корневого script исполняемого пользователями, не являющимся пользователем root, будет красным. Я рекомендую вам не контролировать доступ с помощью проверки if
.
chown root:root script.sh
chmod u=rwx,go=r script.sh
В этом ответе, чтобы было ясно, я предполагаю, что читатель может читать сценарии оболочки bash
и POSIX, такие как dash
.
Я полагаю, что здесь мало что можно объяснить, потому что ответы с большим количеством голосов объясняют многое из этого.
Тем не менее, если есть что-то, чтобы объяснить дальше, не стесняйтесь комментировать, я сделаю все возможное, чтобы заполнить пробелы.
A few answers have been given, but it appears that the best method is to use is:
id -u
- If run as root, will return an id of 0.
This appears to be more reliable than the other methods, and it seems that it return an id of 0 even if the script is run through sudo
.
Check for root:
ROOT_UID=0 # Root has $UID 0.
if [ "$UID" -eq "$ROOT_UID" ]
then
echo "You are root."
else
echo "You are just an ordinary user."
fi
exit 0
Tested and running in root.
#!/bin/bash
# GNU bash, version 4.3.46
# Determine if the user executing this script is the root user or not
# Display the UID
echo "Your UID is ${UID}"
if [ "${UID}" -eq 0 ]
then
echo "You are root"
else
echo "You are not root user"
fi
Editor’s note: If you don’t need double brackets, use single ones for code portability.
test `whoami` != "root" && echo Please run as root && exit 1
Tested under Debian, Ubuntu and Docker.
Check if you are root and quit if you are not:
if ((EUID != 0)); then
echo "Root or Sudo Required for script ( $(basename $0) )"
exit
fi
Or in this example, try to create a directory in root location then try after rights were elevated.
Check if you are root and if not elevate if possible :
# Fails to create these dirs (needs sudo)
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)
if ((EUID != 0)); then
echo "Granting root privileges for script ( $(basename $0) )"
if [[ -t 1 ]]; then
sudo "$0" "$@"
else
exec 1> output_file
gksu "$0" "$@"
fi
exit
fi
echo "Root privileges granted..."
# Creates Dirs as it now has rights
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)
But Teo what that means?
For instance, lets check this script install-app.sh
:
#!/bin/bash
ROOT_UID=0 # Only users with $UID 0 have root privileges.
E_NOTROOT=87 # Non-root exit error.
## Prevent the execution of the script if the user has no root privileges
if [ "${UID:-$(id -u)}" -ne "$ROOT_UID" ]; then
echo 'Error: root privileges are needed to run this script'
exit $E_NOTROOT
fi
...
mkdir -vp ~/app/init
touch config
...
touch /home/<user>/app/init/profile
service mysql start
...
If we run using sudo
:
sudo install-app.sh
This will create directories and a config
file will look like this:
##
## ~ (/root)
drwxr-xr-x 17 root root 4096 Nov 23 20:45 ./
drwxr-xr-x 5 root root 4096 Nov 15 19:04 ../
...
drwxr-xr-x 3 root root 4096 Nov 25 14:30 app/
...
drwxr-xr-x 2 root root 4096 Nov 16 19:08 tmp/
## ~/app (/root/app)
drwxr-xr-x 3 root root 4096 Nov 25 14:30 ./
drwxr-xr-x 17 root root 4096 Nov 25 14:33 ../
drwxr-xr-x 2 root root 4096 Nov 25 14:33 init/
## ~/app/init (/root/app/init)
drwxr-xr-x 2 root root 4096 Nov 25 14:33 ./
drwxr-xr-x 3 root root 4096 Nov 25 14:30 ../
-rw-r--r-- 1 root root 0 Nov 25 14:33 config
## /home/<user>/app/conf
drwxr-xr-x 2 <user> <user> 4096 Nov 25 14:43 ./
drwxr-xr-x 3 <user> <user> 4096 Nov 25 14:30 ../
-rw-r--r-- 1 root root 0 Nov 25 14:43 profile
Recommendation
Applying this changes to the script will be like this:
#!/bin/bash
E_NOTROOT=87 # Non-root exit error.
## Prevent the execution of the script if the user has no root privileges
## Check if is sudoer
if ! $(sudo -l &>/dev/null); then
echo 'Error: root privileges are needed to run this script'
exit $E_NOTROOT
fi
...
mkdir -vp ~/app/init
touch config
...
touch /home/<user>/app/init/profile
sudo service mysql start
...
install-app.sh
/home/<user>/app/init
/home/<user>/app/init/config
/home/<user>/app/init/profile
## Defines user home directory
USER_HOME_DIR=$(getent passwd ${SUDO_USER:-$USER} | cut -d: -f6)
...
mkdir -vp "$USER_HOME_DIR/app/init"
...
id -u
is much better than whoami
, since some systems like android may not provide the word root.
# whoami
whoami
whoami: unknown uid 0
As far as I know the correct way to check it is:
if [ $(id -u) = "0" ]; then
echo "You are root"
else
echo "You are NOT root"
fi
See «Testing For Root» section here:
The problem using: id -u, $EUID and whoami is all of them give false positive when I fake the root, for example:
$ fakeroot
$ id -u
0
$ echo $EUID
0
$ whoami
root
$ ls /root/ &>/dev/null && is_root=true || is_root=false; echo $is_root
if [ "$(id -u)" != "0" ]; then
echo "Sorry, you are not root."
exit 1
fi
if [ `id -u` != "0" ]; then
echo "Sorry, you are not root."
exit 1
fi
chown root:root script.sh
chmod u=rwx,go=r script.sh
One simple way to make the script only runnable by root is to start the script with the line:
0- Read official GNU Linux documentation, there are many ways to do it correctly.
1- make sure you put the shell signature to avoid errors in interpretation:
#!/bin/bash
2- this is my script
#!/bin/bash
if [[ $EUID > 0 ]]; then # we can compare directly with this syntax.
echo "Please run as root/sudo"
exit 1
else
#do your stuff
fi
Very simple way just put:
if [ "$(whoami)" == "root" ] ; then
# you are root
else
# you are not root
fi
if [ "$(whoami)" == "john" ] ; then
# you are john
else
# you are not john
fi
In addition, with proper use of sudo
, you could have the script check and see if it is running as root. If not, have it recall itself via sudo
and then run with root permissions.
Depending on what the script does, another option may be to set up a sudo
entry for whatever specialized commands the script may need.
error() {
printf '\E[31m'; echo "$@"; printf '\E[0m'
}
if [[ $EUID -eq 0 ]]; then
error "Do not run this as the root user"
exit 1
fi
This also assumes that you want to exit with a 1 if you fail. The error
function is some flair that sets output text to red (not needed, but pretty classy if you ask me).
In this answer, let it be clear, I presume the reader is able to read bash
and POSIX shell scripts like dash
.
I believe there is not much to explain here since the highly voted answers do a good job of explaining much of it.
Yet, if there is anything to explain further, don’t hesitate to comment, I will do my best by filling the gaps.
How do you check what permissions a user has in Linux?
- ls -l. Then you will see the file’s permissions, like the following: …
- chmod o+w section.txt. …
- chmod u+x section.txt. …
- chmod u-x section.txt. …
- chmod 777 section.txt. …
- chmod 765 section.txt. …
- sudo useradd testuser. …
- uid=1007(testuser) gid=1009(testuser) groups=1009(testuser)
How do I find my root username in Linux?
- su command – Run a command with substitute user and group ID in Linux.
- sudo command – Execute a command as another user on Linux.
What is root in terminal?
Information related to the topic bash check if user is root
Optimized all-round solution for performance and reliability; all shells compatible
# bool function to test if the user is root or not
is_user_root () { [ "${EUID:-$(id -u)}" -eq 0 ]; }
Benchmark (save to file is_user_root__benchmark
)
#+------------------------------------------------------------------------------+
#| is_user_root() benchmark |
#| "Bash is fast while Dash is slow in this" |
#| Language: POSIX shell script |
#| Copyright: 2020-2021 Vlastimil Burian |
#| M@il: info[..]vlastimilburian[..]cz |
#| License: GPL 3.0 |
#| Version: 1.2 |
#+------------------------------------------------------------------------------+
readonly iterations=10000
# intentionally, the file does not have an executable bit, nor it has a shebang
# to use it, just call the file directly with your shell interpreter like:
# bash is_user_root__benchmark ## should take a fraction of one second
# dash is_user_root__benchmark ## could take around 10 seconds
is_user_root () { [ "${EUID:-$(id -u)}" -eq 0 ]; }
print_time () { date +"%T.%2N"; }
print_start () { printf '%s' 'Start : '; print_time; }
print_finish () { printf '%s' 'Finish : '; print_time; }
printf '%s\n' '___is_user_root()___'; print_start
i=1; while [ "$i" -lt "$iterations" ]; do
is_user_root
i=$((i+1))
done; print_finish
Examples of use and duration:
$ dash is_user_root__benchmark
___is_user_root()___
Start : 03:14:04.81
Finish : 03:14:13.29
$ bash is_user_root__benchmark
___is_user_root()___
Start : 03:16:22.90
Finish : 03:16:23.08
Portable pure POSIX solution + Example of usage of the above function
#!/bin/sh
# bool function to test if the user is root or not (POSIX only)
is_user_root () { [ "$(id -u)" -eq 0 ]; }
if is_user_root; then
echo 'You are the almighty root!'
exit 0 # implicit, here it serves the purpose to be explicit for the reader
else
echo 'You are just an ordinary user.' >&2
exit 1
fi
See some more details on the topic bash check if user is root here
How do I check if I have root access? – Unix Stack Exchange
Yes. If you are able to use sudo to run any command (for example passwd to change the root password), you definitely have root access.
Check the bash shell script is being run by root or not – nixCraft
Check if user is root/sudo before running a script – The Electric …
How do I check if a user has root access in Linux? – OS Today
Explanation
Объяснение
Так как чтение переменной bash
стандарта во много раз быстрее, эффективный идентификатор пользователя, чем выполнение команды id -u
для POSIX -ly, находит пользователя ID, это решение объединяет оба в красиво упакованную функцию. Если и только если $EUID
по какой-либо причине недоступен, команда id -u
будет выполнена, гарантируя, что мы получим правильное возвращаемое значение независимо от обстоятельств.
How do I access root?
In most versions of Android, that goes like this: Head to Settings, tap Security, scroll down to Unknown Sources and toggle the switch to the on position. Now you can install KingoRoot. Then run the app, tap One Click Root, and cross your fingers. If all goes well, your device should be rooted within about 60 seconds.
How do I know if user is root or sudo?
Bash script to check if a specific user is present in etc passwd
https://youtube.com/watch?v=tQ9VDxCmiKk%3F
Images related to the topicBash script to check if a specific user is present in etc passwd

How do you find if a user has permissions on a particular file?
Check Permissions in Command-Line with Ls Command
If you prefer using the command line, you can easily find a file’s permission settings with the ls command, used to list information about files/directories. You can also add the –l option to the command to see the information in the long list format.
How do you check user permissions in Unix?
To view the permissions for all files in a directory, use the ls command with the -la options. Add other options as desired; for help, see List the files in a directory in Unix. In the output example above, the first character in each line indicates whether the listed object is a file or a directory.
How do I give a user root access in Linux?
- To add a user to root using usermod, we have to run the following command in the terminal. …
- To add an existing user to the root group, follow the following command: usermod -g 0 -o user. …
- useradd command can be used to create a new user or update default new user information. …
- Example:
Is a root user in Linux?
Complete Shell Scripting | Run shell script with root user or with sudo privilage
https://youtube.com/watch?v=Ot5AjcCSBoQ%3F
Images related to the topicComplete Shell Scripting | Run shell script with root user or with sudo privilage

What does chmod 777 mean?
777 – all can read/write/execute (full access). 755 – owner can read/write/execute, group/others can read/execute. 644 – owner can read/write, group/others can read only.
How do I login as root in terminal?
Part 1 of 5:
- linux bash check if user is root
- bash check if variable is set
- how to check if user is superuser
- bash script check if user is root
- bash root directory
- bash script run as root
- bash if
- check root users
- bash if else
- ubuntu check if user is root
- how to check root user in kali linux
- bash check if file exists
- bash check if directory exists
Why I post this solution after so many years the OP has asked
Well, if I see correctly, there does seem to be a missing piece of code above.
You see, there are many variables which have to be taken into account, and one of them is combining performance and reliability.
What is the user ID of root?
Shell Script Check If Directory Exists – Folder – Linux – BASH – tutorial
Shell Script Check If Directory Exists – Folder – Linux – BASH – tutorial
Shell Script Check If Directory Exists – Folder – Linux – BASH – tutorial
https://youtube.com/watch?v=dqdjNf6Z1-U%3F
Images related to the topicShell Script Check If Directory Exists – Folder – Linux – BASH – tutorial

Заключение
Как бы вам это ни нравилось, среда Unix/Linux очень разнообразна. Это означает, что есть люди, которым так нравится bash
, что они даже не думают о переносимости (POSIX оболочки). Другие, как я, предпочитают POSIX оболочки. В настоящее время это вопрос личного выбора и потребностей.
попробуйте следующий код:
if [ "$(id -u)" != "0" ]; then
echo "Sorry, you are not root."
exit 1
fi
if [ `id -u` != "0" ]; then
echo "Sorry, you are not root."
exit 1
fi
Один простой способ сделать скрипт доступным только для пользователя root – запустить скрипт со строкой:
Насколько я знаю, правильный способ проверить это:
if [ $(id -u) = "0" ]; then
echo "You are root"
else
echo "You are NOT root"
fi
Смотрите раздел “Тестирование на корень” здесь:
id -u
намного лучше, чем whoami
, поскольку некоторые системы, такие как android, могут не предоставлять слово root.
# whoami
whoami
whoami: unknown uid 0
Проверьте, являетесь ли вы пользователем root, и выйдите из системы, если вы не:
if ((EUID != 0)); then
echo "Root or Sudo Required for script ( $(basename $0) )"
exit
fi
Или в этом примере попытайтесь создать каталог в корневом расположении, а затем попытайтесь после повышения прав.
Проверьте, являетесь ли вы пользователем root и, если возможно, не повышать его:
# Fails to create these dirs (needs sudo)
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)
if ((EUID != 0)); then
echo "Granting root privileges for script ( $(basename $0) )"
if [[ -t 1 ]]; then
sudo "$0" "$@"
else
exec 1> output_file
gksu "$0" "$@"
fi
exit
fi
echo "Root privileges granted..."
# Creates Dirs as it now has rights
mkdir /test-dir-$(basename $0)
rmdir /test-dir-$(basename $0)
#!/bin/bash
# GNU bash, version 4.3.46
# Determine if the user executing this script is the root user or not
# Display the UID
echo "Your UID is ${UID}"
if [ "${UID}" -eq 0 ]
then
echo "You are root"
else
echo "You are not root user"
fi
Примечание редактора: если вам не нужны двойные скобки, используйте одинарные для переносимости кода.
Проверьте наличие рута:
ROOT_UID=0 # Root has $UID 0.
if [ "$UID" -eq "$ROOT_UID" ]
then
echo "You are root."
else
echo "You are just an ordinary user."
fi
exit 0
Протестировано и работает в корне.
Conclusion
As much as you possibly don’t like it, the Unix / Linux environment has diversified a lot. Meaning there are people who like bash
so much, they don’t even think of portability (POSIX shells). Others like me prefer the POSIX shells. It is nowadays a matter of personal choice and needs.
if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
if [[ `id -u` -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
I think the best way when using bash is to use $EUID
, from the man page:
EUID Expands to the effective user ID of the current user, initialized
at shell startup. This variable is readonly.
if (( $EUID != 0 )); then
echo "Please run as root"
exit
fi
A way I approach that kind of problem is by injecting sudo
in my commands when not run as root. Here is an example:
SUDO=''
if (( $EUID != 0 )); then
SUDO='sudo'
fi
$SUDO a_command
If your script is always to be run by root, simply set the rights accordingly (0500
).
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit
fi
Related Query
More Query from same tag
Почему я публикую это решение после стольких лет, когда ОП спросил
Что ж, если я правильно вижу, кажется, что выше отсутствует фрагмент кода.
Видите ли, есть много переменных, которые необходимо учитывать, и одна из них сочетает в себе производительность и надежность.
Оптимизированное bash решение для производительности и надежности
#!/bin/bash
is_user_root()
# function verified to work on Bash version 4.4.18
# both as root and with sudo; and as a normal user
{
! (( ${EUID:-0} || $(id -u) ))
}
if is_user_root; then
echo 'You are the almighty root!'
else
echo 'You are just an ordinary user.'
fi
Портативное решение POSIX solution
#!/bin/sh
is_user_root()
# function verified to work on Dash version 0.5.8
# both as root and with sudo; and as a normal user
{
[ "$(id -u)" -eq 0 ]
}
if is_user_root; then
echo 'You are the almighty root!'
else
echo 'You are just an ordinary user.'
fi