Error writing permission denied linux

This article will teach you quickly what is permission denied Linux error. And also what ways you can avoid permission denied error in Linux.

This article will teach you quickly what is permission denied Linux error. And also what ways you can avoid permission denied error in Linux.permission denied Linux


This error comes when you try to list files or try execute the file inside the directory where you don’t have sufficient permission. Since Linux operating system is very particular about its security aspect.

Example of Permission denied Linux error

Let’s say you are a normal user who is trying to list or trying change the directory inside the /root file-system. Since you do not have sufficient permissions system will respond with permission denied error message as below:

[root@rhel ~]# su - manmohan
Last login: Wed Jan 24 14:34:36 UTC 2018 on pts/0
[manmohan@rhel ~]$ ls -l /root
ls: cannot open directory /root: Permission denied
[manmohan@rhel ~]$ cd /root
-bash: cd: /root: Permission denied
[manmohan@rhel ~]$ id
uid=501(manmohan) gid=501(manmohan) groups=501(manmohan)
[manmohan@rhel ~]$

One way to avoid such error is to switch to root user using su – command. However this solution is not recommended since it will gain unnecessary access to all the root file system.

How to resolve Permission denied Error

  • Resolving Permission denied error related to script execution:

Let’s say you have created a shell script for performing any task. but when you try to execute the script you may end with below error due absence of permission denied error.

[root@rhel tmp]# ./myshell.sh
-bash: ./myshell.sh: Permission denied
[root@rhel tmp]#

Now to avoid such case you need to add execute permission “x” to the file myshell.sh using chmod command as below:

[root@rhel tmp]# ls -l myshell.sh
-rw-r--r-- 1 root root 27 Jan 25 00:31 myshell.sh
[root@rhel tmp]# chmod u+x myshell.sh
[root@rhel tmp]# ls -l myshell.sh
-rwxr--r-- 1 root root 27 Jan 25 00:31 myshell.sh
[root@rhel tmp]#

In the last output you can see that there is “x” (execution) permission added after chmod command. So next time when you try to execute the shell script , it will execute without any error.

[root@rhel tmp]# cat myshell.sh
echo "My name is Manmohan"
[root@rhel tmp]# ./myshell.sh
My name is Manmohan
[root@rhel tmp]#

Resolving permission denied Linux error while listing or writing to a file

In this type of permission denied error you try to list or write the file in which you do not have sufficient permission to do so as below:

[manmohan@rhel tmp]$ cd myfolder/
-bash: cd: myfolder/: Permission denied
[manmohan@rhel tmp]$

If you look at the permissions of the “myfolder” directory using ls -l command you will come to know about the permissions.

[root@rhel tmp]# ls -ltr
total 4
drwx------ 2 root root 4096 Jan 25 00:48 myfolder
[root@rhel tmp]# pwd
/tmp
[root@rhel tmp]#

As per the permission given in above output only owner of the directory who is root can have all permission that is read, write and execute.  So in such case you need to change the permission of the directory to read using below chmod command:

[root@rhel tmp]# chmod o+rx myfolder/
[root@rhel tmp]# ls -lt
total 4
drwx---r-x 2 root root 4096 Jan 25 00:48 myfolder
[root@rhel tmp]#

Now this time when normal user manmohan try to list directory he will not get the permission denied error.

[manmohan@rhel tmp]$ ls -lt myfolder/
total 0
[manmohan@rhel tmp]$ cd myfolder/
[manmohan@rhel myfolder]$

In case you want to have write permission on this directory you need to specify w flag as well in chmod command as below:

[root@rhel tmp]# chmod o+rwx myfolder/
[root@rhel tmp]# ls -lt
total 4
drwx---rwx 2 root root 4096 Jan 25 00:48 myfolder
[root@rhel tmp]#

Same is applicable to file level permission as well.

One more way is to changing the ownership of the directory using chown command. Since in our example we are getting error for user manmohan we will change ownership of the directory  “myfolder” using below command.

[root@rhel tmp]# chown manmohan:manmohan myfolder/
[root@rhel tmp]# ls -l
total 4
drwx---rwx 2 manmohan manmohan 4096 Jan 25 00:48 myfolder
[root@rhel tmp]#

Since manmohan user is now the owner of the directory he can able to do any operation on the directory. In case you want to recursive permission do not forget to add -r while chown command as below:

[root@rhel tmp]# chown -R manmohan:manmohan myfolder/
  • Resolving permission denied Linux error for specific user

In above method of changing the permission using chmod is not suitable as per my opinion. Because when you give permission to others, it will be open for all the users within the system. Which is wrong in terms of security perspective.  To resolve this error specific to user you can implement it using access control list or ACL. Follow my article on Access control list ACL for the same.


Download Free book

Get your free copy of Linux command line Cheat Sheet!!!!

Download This Book: Click Here!!

Linux is a community of open-source Unix-like operating systems that are based on the Linux Kernel. Linux distributions are constructed in such a secured way that a user cannot make changes unless he/she has administration access. Users who are first time exploring Linux encounter the problem of Permission being Denied. In this article, we will learn how to fix them with the following methods.

  • Sudo command missing
  • Insufficient permissions to access the files
  • Change ownership of the file

Let’s explore all the methods one by one.

Method 1: Sudo command missing

Step 1: This is one of the very common mistakes that experienced Linux users also make and has nothing wrong with your system or files. The sudo command allows you to access the files, and folders, and change settings that are accessible to only a root user. For example, here we are installing a new application and the user who is installing should be a root user. 

First, we enter the command

apt-get install neofetch

And we get the following error.

Step 2: Now add the sudo command, after entering the following command, you are required to enter the password.

sudo apt-get install neofetch

The output is as follows:

Method 2: Insufficient permissions to access the files

Step 1: Some files don’t have the required permission for accessing. In the following example, we want to read a file but we don’t have sufficient permissions.

$ cat geeks.txt

The output is 

Step 2: Now we will change the access permission using the chmod command. The +rwx adds the read-write access.

$ chmod +rwx geeks.txt
$ cat geeks.txt

The output is as follows

The chmod has the following commands:

  • r: It means the read permission.
  • w: It means write permissions
  • x: It means execution permissions.
  • +: It provides permission. 
  • : It removes the permission. 

Method 3: Change ownership of the file

This also gives a Permission Denied error to a user in a mixed system when the user doesn’t have the access to a particular file. We can add users using the chown command.

Step 1: First, check the users who have access using the following command.

ls -l

Only a single user and a single group have access to read, write and execute as can be seen in the output.

Step 2; Now add the user geeks using the following command.

sudo chown geeks geeks.txt

Now check the owners of the file. The output is as follows:

So the user geeks now has the access to the text file.

When working with Linux, one often run into a Permission denied error. This is probably the most common error one runs into when starting on Linux. In this module we would learn how to fix this error in multiple ways.

Steps to fix the permission denied error on Ubuntu/Debian Linux

Let’s go over the steps to fix the permission denied error on our Ubuntu or Debian based systems here.

Method 1: Use the Sudo Command

There are some files that are owned by root and can be accessed only by the root user or can be accessed with the sudo command. It is not advisable to change the permissions or the ownership of these files. However, if needed, they can be modified with superuser permissions. Examples of such files are :

  • /etc/shadow
  • sudoers file
  • systemwide config files

To access such files, we need to use sudo or be a root user as such :

$ whoami
root
$ cat /etc/shadow
< Contents >

Or ,

$ whoami 
user
$ id
uid=1000(user) gid=1000(user) groups=1000(user),27(sudo)
$ sudo cat /etc/shadow
< Contents >

Method 2: Setting the Right System Permissions

This is the most common way of fixing this operation. Often, we lack the necessary permissions to access a file. To check our available permissions, we can use the ls command:

Let’s assume that this results in the following output :

$ ls -l
total 4
-rw------- 1 user user 20 Feb 12 11:36 Test

Here we can see that only the owner user has read and write permissions. Thus if another user tries to read this file, they will get an error as such:

$ whoami
user1
$ cat /home/user/Test
cat: /home/user/Test: Permission denied

Hence, to fix this, we would use the chmod command. We can provide read access to everyone (the owner, the group members and others) with the following command :

Checking the permissions on the file now should yield something like the following :

$ ls -l 
total 4
-rw-r--r-- 1 user user 20 Feb 12 11:36 Test

The same can be done with write and execute permissions. If we want to limit the access to the users of the same group, we can use the following command :

This would allow the users in the same group as that of the owner to access the file and the permissions would look something like this :

$ ls -l
total 4
-rw-r----- 1 user user 20 Feb 12 11:36 Test

Now, we can finally read the file as the other user.

$ whoami
user1
$ cat /home/user/Test
This Is A Test File

NOTE : If the file is owned by the root user and our current user is in the sudoer’s group then we can ourselves change the permissions of the file by prefixing our commands with sudo. To know more about the usage of the chmod command check out this module !

Method 3: Change Ownership Of The File

The last method on our list, albeit less conventional, can help fix the Permission denied error. Instead of changing the permissions of the file, here we will change its ownership. For this, we would need the chown command. First let us check the ownership of the file using:

$ ls -l
total 4
-rw------- 1 user user 20 Feb 12 13:27 Test

As we can see, the file belongs to the user labeled as ‘user‘ and also the group by the same name. Also, notice how only the owner has read and write permissions (these can be changed as discussed previously). However, at present, we cannot access the file. But we’ll change the ownership (and group) of the file with :

$ sudo chown user1:mygroup /home/user/Test

If we check the details on our file now, we would find it to be changed to :

-rw------- 1 user1 my-group   20 Feb 12 13:27 Test

As we can see, the permissions on the files are preserved, but the groups that can access the file are changed. Since the owner has read permissions (if that’s not the case, we can always use chmod), we can now read the file’s contents:

$ cat /home/user/Test
This Is A Test File

Conclusion

Here, we saw how to solve issues with permissions. The methods described here each have their own applicability depending on the scenarios and each must be used carefully as required.



30 Nov, 22



by Susith Nonis



5 min Read

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

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

Using the Nano text editor, I’m trying to save and exit a file.
I already have the file named.

I click Ctrl+X to exit. And then I click Y because I want to save the file. It asks for file to write, I pressed Enter to use the default name because its already named.

The problem is I get this message.

[Error writing /filename: Permission denied]

What am I doing wrong?

Related Solutions

Ubuntu – Nano – insert content, save and exit

I may have misunderstood your question. SHH doesn’t exist, do you mean SH or SSH? Or maybe Bash? (EDIT: brought an edit to fix this)

Anyway, nano won’t be much of assistance here. echo will.

echo "ServerName localhost" > /etc/apache2/conf-available/fqdn.conf
sudo a2enconf fqdn

The above shell code will send your text into the file. Replacing > with >> will append it instead, if that’s what you’re looking for.

If you need root privileges to write to this file, then use tee instead of a simple shell redirection (>/>>). This will allow you to use sudo properly:

echo -e "ServerName localhost" | sudo tee -a /etc/apache2/conf-available/fqdn.conf
sudo a2enconf fqdn

nano is here so that you, the user, can write data manually into a file. However, if you’re looking for an automated process, there’s no need for an editor, coreutils can handle that just fine. Linux doesn’t need the fancy nano interface to write into a file.

Ubuntu – Saving file in nano to specific folder

Nano by default saves to the current working directory (CWD) or to the relative path from your CWD to the file that is open. If you want to save to another directory you just prepend the filename with the path

For example

Ctrl+O opens the save prompt

File Name to Write: ~/test.txt

Will save test.txt to my home directory

File Name to Write: ../test.txt

Will save test.txt to one directory above my CWD

File Name to Write: /absolute/path/to/file/text.txt

Will save text.txt in /absolute/path/to/file/ directory

After you save a file nano will be using that path in the buffer. To see that path Ctrl+O opens the save prompt with the new relative path Ctrl+C to cancel saving

While in the save prompt Ctrl+T opens a handy file browser you can use

Все операционные системы семейства 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: 26 831

Понравилась статья? Поделить с друзьями:
  • Error unterminated procedure maple
  • Error unterminated comment
  • Error unsupported type 51906
  • Error unsupported partition unaligned
  • Error unsupported operand types