Ошибка bash permission denied linux

Многие новички пытаются выполнить запись определенных значений в системные файлы с помощью операторов перенаправления ввода и вывода и получают ошибку 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 License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

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

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

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

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

    Ошибка «Permission Denied»

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

  2. Проверяем права доступа к содержимому каталога, набрав «ls -l». Результат, полученный для текстового документа, выделен рамкой. Разрешение на чтение и запись имеет только его владелец.

    Просмотр прав доступа командой «ls»

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

  3. Набираем команду «sudo chmod 755 filename». С ее помощью мы от имени администратора системы даем разрешение на чтение документа себе и любому другому пользователю. Проверяем результат выполнения и убеждаемся, что права доступа изменились нужным образом.

    Изменение прав доступа командой «chmod»

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

  4. Повторно используем «cat» и читаем ранее недоступное содержимое.

    Просмотр текстового файла командой «cat»

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

Загрузка ... Загрузка …

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

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

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

    Графический вариант ошибки «Permission Denied»

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

  2. Разворачиваем меню «Файл». Выбираем в списке действий «Открыть как Администратор».

    Переключение файлового менеджера в режим root

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

  3. Вводим в отмеченное стрелкой поле пароль root. Нажимаем кнопку «Аутентификация» или клавишу Enter.

    Окно аутентификации root

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

  4. В новом окне файлового менеджера вызываем контекстное меню для нужного файла. Выбираем в нем пункт «Параметры».

    Контекстное меню файлового менеджера

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

  5. Переключаемся на вкладку «Права». Меняем разрешения для группы и остальных пользователей. Для последних выберем в качестве примера «Только чтение». Внеся изменения, закрываем окно параметров.

    Вкладка «Права» в свойствах файла

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

  6. Теперь текстовый документ будет открываться в выбранном нами режиме «Только чтение», без возможности редактировать содержимое.

    Файл, открытый в режиме чтения

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

Загрузка ... Загрузка …

В заключение

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

Загрузка ... Загрузка …

Post Views: 29 204


Posted:
21 Feb, 22


Updated:
05 Mar, 23



by Susith Nonis



5 Min

How to fix 'permission denied' error in Linux? [Solutions]

List of content you will read in this article:

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

check the permission on the file with

ls -l /path/to/your/file

you should see something like

-rw-r--r--

r mean readable, w writeable, and x executable.

the first set is for your user, the second set of three is for your group, and the third set is for anyone.

so in my example, the file i have shown is read/write for me, and read only for my group and for any other user.

Use the chmod command to change permissions.

chmod 744 file

will make the file read/write/exec for you, and just read for user/world.

Files on an operating system usually have permissions, making the file accessible to a limited range of people. For instance, some files on a computer are accessible only to administrators; other files are only accessible to a particular user.

If you try to run a file to which you have no access on a Linux computer, you will see a permission denied error. In this guide, we’re going to talk about the cause of this error and how you can solve the error. Let’s begin.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Bash permission denied

The Bash permission denied error happens when you try to run a file which you do not have permission to run. This may happen if a file can only be executed by a particular user or a group of which you are not a member.

On a Linux operating system, there are three types of permissions:

  • Read
  • Write
  • Execute

You can have permission to read and write a file without having execution privileges. Thus, if you encounter a Bash permission denied be sure to check whether you are allowed to run the file. You can check if you have permissions over a file by using the following command:

ls -la

This command will give you information about file permissions. We discuss the output of this command in our The Solution section later in the article. Let’s look at an example scenario featuring the permission denied error, with a corresponding solution.

An Example Scenario

We have a file called example.sh. We can see this file by running the ls command. The ls command returns the following:

We want to run our example.sh file. To do so, we can use the ./ notation:

This command lets us run the example.sh file which is present in our ./ directory (the directory we are presently viewing). Let’s see what happens when we try to run the file:

bash: ./test.sh: Permission denied

Our command returns an error.

The Solution

Our Bash shell is telling us that we do not have permissions to run our file. We can check what permissions we have by running the ls -la command:

-rw-r----- 1 james james 13 Feb 16 12:48 example.sh
-rw-r----- 1 james james 13 Feb 16 12:48 example1.sh

We do not have execution privileges over any of our files. If there were an x after the rw in the first entry of the output above, we would know we can execute our file. The three characters after the first one represent read, write, and execute privileges for a user. Our group also does not have write or execute permissions.

To solve this issue, we need to give ourselves execution privileges:

This command gives our user execution (“x”) privileges over the example.sh file.

We can only run this command if we are allowed to change the privileges of the file. If this file was protected (owned by root, for example), then we would not be able to change this file.

The file is owned by the james system user so I can alter the file permissions on my james account. I could also use sudo to alter the file privileges, although this is not necessary because my user account has the necessary access.

Conclusion

The Bash permission denied error indicates you are trying to execute a file which you do not have permission to run. To fix this issue, use the chmod u+x command to give yourself permissions. If you cannot use this command, you may need to contact your system administrator to get access to a file.

Do you want to learn more about Bash? Check out our How to Learn the Command Line guide. This guide comes with top tips on how to learn Bash. You will also find a list of resources to help you accelerate your learning journey.

  • Ошибка base game not installed
  • Ошибка bc на котле кентатсу что делать
  • Ошибка bas на мерседес w203 что значит
  • Ошибка battleye query timeout
  • Ошибка bas ets w210