Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку bash permission denied. Эта ошибка выводится, даже если вы использовали sudo.
Казалось бы, sudo есть, значит права суперпользователя получены и все должно работать но тут все не так просто. В этой статье мы рассмотрим почему возникает ошибка bash permission denied и как ее обойти.
Допустим, вы выполняете команду:
sudo echo "nameserver 8.8.8.8" >> /etc/resolv.conf
А в результате вместо записи строчки в /etc/resolv.conf получаете ошибку:
bash: /etc/resolv.conf permission denied
В русской локализации это будет отказано в доступе bash linux. Так происходит потому что вы запускаете с правами суперпользователя утилиту echo и она честно выводит вашу строку в стандартный вывод bash с правами суперпользователя. Но bash запущен от обычного пользователя, и когда интерпретатор bash пытается записать полученную строчку в системный файл, естественно, что вы получите ошибку.
Но существует несколько способов обойти это ограничение, вы можете, например, использовать команду tee, которая записывает стандартный вывод в файл или запустить саму оболочку от имени суперпользователя. Рассмотрим сначала вариант с tee:
echo ‘текст’ | sudo tee -a /путь/к/файлу
echo 'nameserver 8.8.8.8' | sudo tee -a /etc/resolv.conf
Это очень простое решение, но, кроме того, вы можете запустить оболочку bash с правами суперпользователя, чтобы дать ей доступ на запись:
sudo sh -c ‘echo текст >> /путь/к/файлу’
sudo bash -c ‘echo текст >> /путь/к/файлу’
Например:
sudo bash -c 'echo nameserver 8.8.8.8 >> /etc/resolv.conf
Еще одно решение, призванное, упростить эту команду, добавить такой код в ~/.bashrc:
sudoe() {
[[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1
echo "$1" | sudo tee --append "$2" > /dev/null
}
Дальше для вывода строки в файл выполняйте:
sudoe ‘текст’ >> /путь/к/файлу
Например:
sudoe "nameserver 8.8.8.8" > /etc/resolv.conf
Теперь все будет работать, как и ожидалось, и ошибка bash отказано в доступе не появится. Еще можно поменять права на файл, а потом уже выводить в него строку. Но это очень неправильное решение. И даже не потому, что это небезопасно, а больше потому что там намного больше действий.
Выводы
В этой небольшой статье мы разобрали почему возникает ошибка bash permission denied при использовании команды echo для системных файлов, а также несколько путей ее решения. Как видите, все достаточно просто. Надеюсь, эта информация была полезной для вас.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
Все операционные системы семейства Linux имеют четко разграниченные права доступа. В своей домашней директории пользователь может делать все, что ему угодно, до тех пор, пока укладывается в отведенные рамки. Попытка выйти за них приводит к появлению ошибки «Permission Denied».
Изменение прав в терминале
Рассмотрим вариант, в котором необходимо прочесть текстовый документ, созданный другим пользователем. Файлы TXT в Linux можно просматривать непосредственно в терминале с помощью команды «cat».
- Заходим в каталог с интересующим нас документом. Набираем команду «cat filename», подставляя вместо «filename» имя нужного файла. На скриншоте показана ошибка «Permission Denied», выглядящая в русской локализации как «Отказано в доступе».
Получаем ошибку «Permission Denied» при попытке просмотреть содержимое файла
- Проверяем права доступа к содержимому каталога, набрав «ls -l». Результат, полученный для текстового документа, выделен рамкой. Разрешение на чтение и запись имеет только его владелец.
Проверяем права доступа к документу используя команду «ls -l»
- Набираем команду «sudo chmod 755 filename». С ее помощью мы от имени администратора системы даем разрешение на чтение документа себе и любому другому пользователю. Проверяем результат выполнения и убеждаемся, что права доступа изменились нужным образом.
Используем команду «chmod» и административные права для получения доступа
- Повторно используем «cat» и читаем ранее недоступное содержимое.
Просматриваем содержимое текстового документа командой «cat»
Загрузка …
Изменение прав в файловом менеджере
Разберемся, как выполнить рассмотренную выше операцию в графическом интерфейсе, используя файловый менеджер из дистрибутива.
- Как видно на скриншоте, значок файла изначально имеет дополнительные символы, указывающие на то, что доступ у нему ограничен. При попытке посмотреть содержимое получаем графический вариант ошибки «Permission Denied».
При попытке открыть текстовый документ получаем ошибку «Permission Denied»
- Разворачиваем меню «Файл». Выбираем в списке действий «Открыть как Администратор».
Открываем меню «Файл» и перезапускаем файловый менеджер от имени root
- Вводим в отмеченное стрелкой поле пароль root. Нажимаем кнопку «Аутентификация» или клавишу Enter.
Набираем пароль root в окне аутентификации
- В новом окне файлового менеджера вызываем контекстное меню для нужного файла. Выбираем в нем пункт «Параметры».
Открываем параметры файла с помощью контекстного меню
- Переключаемся на вкладку «Права». Меняем разрешения для группы и остальных пользователей. Для последних выберем в качестве примера «Только чтение». Внеся изменения, закрываем окно параметров.
На вкладке «Права» разрешаем доступ для группы root и остальных пользователей
- Теперь текстовый документ будет открываться в выбранном нами режиме «Только чтение», без возможности редактировать содержимое.
Открываем ранее недоступный файл в режиме чтения и изучаем содержимое
Загрузка …
В заключение
Как видим, избавиться от ошибки Permission Denied достаточно просто. Решив изменить правда доступа к системным файлам, лишний раз убедитесь, что полностью уверены в своих действиях и понимаете последствия вносимых изменений.
Загрузка …
Post Views: 29 081
I have a weird problem, I cant execute bash script even as basic as:
#!/bin/bash
echo "me"
I am saving it as a test.sh and then do chmod 755 test.sh and once run ./test.sh getting:
bash: ./test.sh: Permission denied
Any ideas what could be causing this?
tripleee
173k33 gold badges269 silver badges313 bronze badges
asked Nov 11, 2011 at 14:19
1
That can happen if you have mounted the file system with the «noexec» option. You should remove it.
apaderno
28.3k16 gold badges75 silver badges90 bronze badges
answered Nov 11, 2011 at 14:21
themelthemel
8,8232 gold badges32 silver badges31 bronze badges
3
Script needs be executable. Use this:
chmod +x <script-name>
answered Apr 20, 2017 at 21:30
AbhinavAbhinav
3193 silver badges8 bronze badges
2
Although not directly pertinent to this particular thread; if a file has come form a Windows system there may be a CR/LF at the end of the line. This would affect all lines in the file, including the initial execution line, and would not be visible if you are viewing the file.
$ ./test.sh
-bash: ./test.sh: /bin/bash^M: bad interpreter: No such file or directory
To see this, you could cat -A the file:
$ cat -A ./test.sh
#!/bin/bash^M$
echo «me»^M$
To remove, use dos2unix.
answered Apr 19, 2012 at 11:33
Try
ls -la
to see the actual rights and ownership of the file. To see if the chmod command actually worked. You might want to change the ownership along with the mod of the file check : http://www.tuxfiles.org/linuxhelp/fileowner.html
answered Nov 11, 2011 at 14:25
StainedartStainedart
1,9294 gold badges32 silver badges53 bronze badges
Use chmod +x ./test.sh
this should allow you to run it.
answered Jul 19, 2014 at 15:35
SeremSerem
211 bronze badge
1
Also, check to see if the directory/filesystem containing the script is nfs-mounted. root won’t run scripts from nfs-mounted locations.
answered Mar 22, 2016 at 20:13
1
In macOS this can occur if a com.apple.quarantine flag exists. If you see a @ suffix on the permissions after running a ls -l
on the script’s path, execute ls -l@ *script_path*
to confirm. Then run a xattred -d com.apple.quarantine *script_path*
to remove the quarantine flag.
answered Oct 23, 2020 at 18:10
you need use ./test.sh
when you in the directory of that file,if you don’t,try PATH TO THE SCRIPT
.or you can copy it to some directory of /data
and chmod it for shell,then do the above steeps.if you still fail,it’s ok because i have a same problem,i just did it success for once time.
answered Jul 20, 2016 at 15:57
Lan…Lan…
1051 silver badge6 bronze badges
3
For filesystems which are mounted with the noexec
by default, for example NFS, explicitly adding exec
at the end helps, even when options provided earlier in the list default imply noexec
as well, e.g. the user
option.
So if you have one of those options:
noexec
user
Change them to:
exec
oruser,exec
It is important to place exec
at the end. Just removing noexec
may help in certain cases, but not in all, if you are using other options like user
before.
answered Dec 23, 2020 at 21:03
sebixsebix
2,9432 gold badges28 silver badges43 bronze badges
Posted:
21 Feb, 22
Updated:
05 Mar, 23
by Susith Nonis
5 Min
List of content you will read in this article:
- 1. What is Linux Permission Denied Error?
- 2. How To Fix Permission Denied Error in Linux?
- 3. Representation of permissions
- 4. How to Solve Bash Permission Denied?
- 5. Conclusion
In Linux operating system, you cannot execute any command without proper permission. Every file and directory has some permission or privilege (read, write, or execute) associated with them. If you are not authorized to access the file or directory, executing any command on that will result as a “permission denied” error in Linux. This prevalent common can only be resolved by getting the proper access to that file and directory. In this article, we will help you with how to fix the permission denied errors in Linux and what type of error is this with the help of various Linux commands.
What is Linux Permission Denied Error?
This type of error will occur whenever you run a command for which you do not have the execute permission. Similarly, you cannot perform read or write action if you do not have read or write permission for any file or directory. These Linux permissions are the primary reason behind the security of Linux, as they will help in protecting the data from unauthorized access.
Linux system has three types of permissions
1. read permission
2. write permission
3. execute permission
So, if you want to solve a Linux permission denied error, you can check your privileges for the specific file or folder using the following command.
ls -la
This command will display the long listing of all files and folders along with the permission, as shown below.
As shown below, we have created a shell script “hello.sh” without the execute permission. On executing “hello.sh”, you will get a “permission denied” error.
How To Fix Permission Denied Error in Linux?
For solving this error, you need to add the correct permissions to the file to execute. However, you need to be a “root” user or have sudo access for changing the permission. For changing the permission, Linux offers a chmod command. The chmod stands for change mod. This command has a simple syntax, as shown below.
chmod flags permissions filename
- Flags are the additional options that users can set.
- Permissions can either be read, write or execute in the file. You can represent them in symbolic form (r, w, and x) or octal numbers.
- The Filename specifies the file’s name for changing the permissions.
Representation of permissions
Below is the symbolic and octal representation of the user’s permissions while executing the “chmod” command. First, we will understand the representation before using it.
-
Symbolic representation
chmod u=rwx,g=r,o=r file
where-
- r specifies the read permissions
- w specifies the write permissions
- x specifies the execute permissions
- Octal representation-
chmod 744 file
where-
- 4 specifies the read permissions
- 2 specifies the write permissions
- 1 specifies the execute permissions
- 0 means no permissions issued.
How to Solve Bash Permission Denied?
Now, we are aware of the error, as shown below.
Giving the appropriate permission to the user will solve the problem. Thus, we are giving the execute permission to the user to run the “hello.sh” shell script. Execute the below command to provide execute permission.
chmod +x hello.sh
Now, we can see the change in the permission of the “hello.sh” script file. The above command provides the execute permission to the file. As you can see, the root user can make the required changes. If we execute the shell script, we should not get the error. Let’s try by running the below command.
./hello.sh
After executing the “hello.sh”, we get the output that displays the “hello.” Changing permission has solved the problem of bash permission denied.
Conclusion
If you are a regular Linux user, you might have faced the “permission denied” error while executing various commands. This might be due to the incorrect privileges to run that command. Only a root user or user with sudo access can change the permissions for the file or directory you want to access or execute. If you are the correct user to make the required permission changes, you can run the “chmod” command and add the desired permission.
This is all about how you can solve/fix permission denied errors in Linux with the help of the above-listed commands/methods. If you think there are other alternatives to achieve the goal, you can put them down via the comment box. Also, you can buy a Linux VPS server to run and test the above listed commands.
People also read:
- How to fix the sudo command not found error
- How to fix DNS server not responding error
- What is 403 forbidden error
- 500 internal server error: fixed
- How to fix npm command not found error
./geany_run_script.sh: 5: ./geany_run_script.sh: ./Area_circumference: Permission denied
program exited with code: 126
. This problem always occur when I try to execute my code. What might be the solution?
Alvar
16.8k29 gold badges91 silver badges132 bronze badges
asked Jan 22, 2014 at 6:44
5
Here’s a link which explains about Changing file permission (and ownership)
If you want to skip these (for now of course), you can create a directory/folder in your user-home directory and work on your C
programmes (or others) there.
You can open the terminal (press Ctrl + Alt + T) and cd
to the target directory:
cd /path/to/target
To give the file «the_file_name» execute permission (if the file-system allows you with the RW rights):
chmod +x the_file_name
answered Jan 22, 2014 at 7:07
rustyrusty
15.7k10 gold badges65 silver badges92 bronze badges
7
You need to give execute
and read
permissions. Follow this:
chmod u+r+x filename.sh
./filename.sh
When we make a new script file then by default it has read and write permission.
But if we want to execute them, then we should give execute permission as shown above.
Execution bit alone is not enough for shell scripts, one must be able to read the file as well to execute it (contrary to binaries which only need the execute permission bit)
answered Aug 6, 2014 at 4:07
Jay ModiJay Modi
6916 silver badges9 bronze badges
2
Open your terminal application by pressing CTRL
+ ALT
+ T
or with the apposite shortcut on the graphical enviroment (like Terminal
or xTerm
).
In the uniform window which appears on the screen you’ll see a blinking character, it’s the terminal cursor
: simply click on the window and write to enter text (typically commands) and press ENTER
to confirm the input.
Before the cursor there is always listed your current position on the file system from the root directory
(«/») and your home (where your personal files are) is called «~».
To change directory/folder use cd EXISTENTFOLDER
(replace EXISTENTFOLDER with the folder name); if you feel lost, simply type cd
to return to your home directory in a blink!
Now let’s solve your problem:
-
Use the
cd
command to find the directory with your source code. UseTAB
to help you. If you executels -lh
, you’ll see a list of possible paths to follow and files to execute. -
When you’ve find the blocked file execute
chmod +x FILENAME
(replace FILENAME with the name of your source code file). -
If you have multiple blocked files execute
chmod +x *
to unlock all files in the current directory. Never chmod +x dangerous or insecure files. -
Execute
./FILENAME YOUREVENTUALARGUMENTS
to execute your executable file. -
Remember that if your compiled program tries to read/write outside your home directory you’ll need to execute it as
root
by usingsudo ./FILENAME YOUREVENTUALARGUMENTS
.
If you want to have a manual for a command execute man COMMAND
(replace COMMAND with the exact command name, Linux is case sensitive).
Some shells have an Open terminal here
command to simplify your life, search for it in the future and remember that the command shell can be your best friend, if you use it well.
It’s all. If you need more help comment under here.
If I’m helping you press the UP arrow on the left; if you solve mark this answer as best answer.
Have a nice experience on Linux & Ubuntu.
answered Jan 22, 2014 at 10:42
1
Or you can excute it with your shell directly(or other shell versions), if you don’t want to change the permission.
$ bash filename.sh
answered Jul 30, 2022 at 9:57
For the rest of us where the issue isn’t caused by the execute bit not being set, @Avinash-Raj put it best:
Permission denied
error are occurs only if you don’t have enough privilege to access that file.
In my case, it was root lacking permission to access a fuse-based mount.. It really does boil down to whoever the script is run under lacking the necessary permissions to access or run the script.
I’m leaving this obvious/trivial answer here for my fellow fuse users to whom google will absolutely refuse to suggest any solution other than setting the execute bit.
answered Apr 30 at 11:28