Error writing permission denied linux

Ошибка bash permission denied

Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку bash permission denied. Эта ошибка выводится, даже если вы использовали sudo.

Казалось бы, sudo есть, значит права суперпользователя получены и все должно работать но тут все не так просто. В этой статье мы рассмотрим почему возникает ошибка bash permission denied и как ее обойти.

Ошибка 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

Еще одно решение, призванное, упростить эту команду, добавить такой код в

sudoe() <
[[ «$#» -ne 2 ]] && echo «Usage: sudoe

» && return 1
echo «$1» | sudo tee —append «$2» > /dev/null
>

Дальше для вывода строки в файл выполняйте:

sudoe ‘текст’ >> /путь/к/файлу

sudoe «nameserver 8.8.8.8» > /etc/resolv.conf

Теперь все будет работать, как и ожидалось, и ошибка bash отказано в доступе не появится. Еще можно поменять права на файл, а потом уже выводить в него строку. Но это очень неправильное решение. И даже не потому, что это небезопасно, а больше потому что там намного больше действий.

Читайте также:  Show file path windows

Выводы

В этой небольшой статье мы разобрали почему возникает ошибка bash permission denied при использовании команды echo для системных файлов, а также несколько путей ее решения. Как видите, все достаточно просто. Надеюсь, эта информация была полезной для вас.

Источник

Ошибка «Permission denied» в Linux

Все операционные системы семейства Linux имеют четко разграниченные права доступа. В своей домашней директории пользователь может делать все, что ему угодно, до тех пор, пока укладывается в отведенные рамки. Попытка выйти за них приводит к появлению ошибки «Permission Denied».

Изменение прав в терминале

Рассмотрим вариант, в котором необходимо прочесть текстовый документ, созданный другим пользователем. Файлы TXT в Linux можно просматривать непосредственно в терминале с помощью команды «cat».

    Заходим в каталог с интересующим нас документом. Набираем команду «cat filename», подставляя вместо «filename» имя нужного файла. На скриншоте показана ошибка «Permission Denied», выглядящая в русской локализации как «Отказано в доступе».

Получаем ошибку «Permission Denied» при попытке просмотреть содержимое файла

Проверяем права доступа к документу используя команду «ls -l»

Используем команду «chmod» и административные права для получения доступа

Просматриваем содержимое текстового документа командой «cat»

Изменение прав в файловом менеджере

Разберемся, как выполнить рассмотренную выше операцию в графическом интерфейсе, используя файловый менеджер из дистрибутива.

    Как видно на скриншоте, значок файла изначально имеет дополнительные символы, указывающие на то, что доступ у нему ограничен. При попытке посмотреть содержимое получаем графический вариант ошибки «Permission Denied».

При попытке открыть текстовый документ получаем ошибку «Permission Denied»

Открываем меню «Файл» и перезапускаем файловый менеджер от имени root

Набираем пароль root в окне аутентификации

Открываем параметры файла с помощью контекстного меню

На вкладке «Права» разрешаем доступ для группы root и остальных пользователей

Открываем ранее недоступный файл в режиме чтения и изучаем содержимое

В заключение

Как видим, избавиться от ошибки Permission Denied достаточно просто. Решив изменить правда доступа к системным файлам, лишний раз убедитесь, что полностью уверены в своих действиях и понимаете последствия вносимых изменений.

Источник

How to resolve the «Permission Denied» error in Linux

While using Linux, you may encounter the error, “permission denied”. This error occurs when the user does not have the privileges to make edits to a file. Root has access to all files and folders and can make any edits. Other users, however, may not be allowed to make such edits.

Remember that only root or users with Sudo privileges can change permissions for files and folders.

The permissions can be changed using the chmod keyword. The syntax for the command is:

chmod flags permissions filename

  • flags are the additional options users can set.
  • permissions define if the user can read, write, or execute the file. They can be represented using symbolic or octal numbers.
  • filename is the name of the file whose permissions are changed.
Читайте также:  Как восстановить заметки mac os

Here is an example where users can read, write, and execute a file; whereas, group and others can only read it.

Here, each letter has a meaning:

r gives read permissions

w gives write permissions

x gives execute permissions

The same command can be run using octal notation:

Here, each digit represents the sum of the permissions allowed:

4 gives read permissions

2 gives write permissions

1 gives execute permissions

0 gives no permissions

The sum of these permissions is used to represent each type of author.

Источник

Bash return permission denied error when I redirect the output of ls to a file [duplicate]

I’m currently studying shell commands, one of the exercises consists in creating a structure with various directories and subdirectories.

I wrote ls -laR > hello , it was supposed to create a text file named hello . However, I get the following message bash: hello: permission denied , even when I type sudo in the beginning.

The command worked in another Linux distribution. Also, I used a few minutes ago ls -la in the directory where I want to create the file and it gave me this:

According to the first triad I have writing privileges?

2 Answers 2

Because root is the owner of the directory where you want to create hello file and users from the same group and other users doesn’t have permission to write in that directory, you will get bash: hello: permission denied error when you run ls -laR > hello .

Moreover, you will get exactly the same error when you run the same command using sudo in front of it. This because output redirection (the > operator) is done by the shell, not by ls , so sudo has no effect upon it. sudo has effect only on ls -laR . To prevent this, you have to login as root:

Читайте также:  Compress with zip linux

Then you can use redirection:

Otherwise, you can run your bash command in a subshell with root privileges:

Finally, another option, instead to use redirection via the > operator, you can use tee command:

You don’t have to use in this case sudo for ls command because users from the same group with root and all other users have read and execution permission in that directory.

Источник

Ubuntu says «bash: ./program Permission denied» [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed last month .

I am running Ubuntu on computer 1 and computer 2. I compiled a C++ program on computer 1, and I can execute it from the terminal using ./program_name . It runs fine.

However, when I try to do this on computer 2, it says: bash: ./program_name: permission denied

What’s wrong and what can I do about it?

3 Answers 3

chmod u+x program_name . Then execute it.

If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name on the local copy and execute that.

Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name adds permission for the user that owns the file to execute it.

That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec option may be specified for a volume in the Unix fstab file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.

Источник

Оцените статью