Linux delete permission denied

Ошибка 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 отказано в доступе не появится. Еще можно поменять права на файл, а потом уже выводить в него строку. Но это очень неправильное решение. И даже не потому, что это небезопасно, а больше потому что там намного больше действий.

Выводы

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

Источник

How to Delete Permission Denied File/Folder in Linux

When you install any programs with root access on Linux-based operating systems, you may receive a Permission Denied error if you try to delete the remaining files or folders, and as a result, you cannot delete the file or folder.

How to Delete an Undeleted File or Folder in Linux

For example, you are using the Linux Mint or Ubuntu operating system, and you have created a new file/folder on the desktop. Since you are logged in to the system with a non-root user, you can easily delete the file/folder you created.

Читайте также:  Как поменять иконку проводника windows

However, in some cases, when you install a program that requires root access, you may encounter files and folders that cannot be deleted anywhere or on the desktop. Therefore, when you try to delete these files and folders normally, you will receive a Permission Denied error.

On Linux, you can use Terminal to delete such files and folders that cannot be deleted. You can delete files that cannot be deleted using the Linux RM command by switching to Root in the Terminal.

How to Remove Files and Folders by Using Terminal on Ubuntu, Debian, Linux Mint, Kali Linux

We will use the Linux RM command to delete an indelible folder that we encountered on Linux Mint 18/19. On Linux, you can delete files, directories, and folders using the RM command.

To delete undelete files on Linux or delete folders, follow the steps below.

Step 1

As you can see in the image below, there is a folder on Linux Mint that cannot delete. When you try to delete it normally, you will receive a Permission Denied error.

Try to delete the vmware-tools-distrib folder as follows.

Step 2

You will receive a Permission Denied error as in the image below.

Step 3

Open the Terminal on Linux and execute sudo su to access Root, then type your root password and press Enter.

Step 4

On Linux, you can use the ls command to display the directory in your current location. To delete the undeleted folder, execute rm -rf vmware-tools-distrib.

Step 5

As soon as you execute the rm -rf vmware-tools-distrib command, you can see that the folder has deleted.

Deleting a File That Cannot Be Deleted ⇒ Video

To delete an undeletable file or folder on Linux Mint 18/19, you can watch the video below and also subscribe to our YouTube channel to support us!

Final Word

In this article, we have examined step by step on how to delete permission denied files or folders. Thanks for following us!

Источник

Linux / Unix Find Command Avoid Permission Denied Messages

W hen I type find . -type d -name «foo» command I get Permission denied error messages. How do I exclude all “permission denied: messages from the find command under Linux or Unix like operating systems?

The find command is used to locate files on a Linux or Unix like operating system. The find command will search directory to match the supplied search criteria. You can search for files by

Tutorial details
Difficulty level Easy
Root privileges No
Requirements find command+
Unix like os
Est. reading time 2m

type, name, owner, group, date, permissions and more. By default the find will search all subdirectories for you. Let us see how to hide and fix permission denied message when using the find on Linux or Unix-like system.

Find command basic syntax

The syntax is as follows:
find where-to-look criteria action
find /dir/to/search -name filetosearch
find /dir/to/search -name «*.c»
find /home/nixcraft/project/ -name «*.py» -print
In this example, find will search the /tmp directory for any files named “data*.txt” and display their pathnames:

Fig. 01: Find will show an error message for each directory on which you don’t have read permission.

How to hide or fix find command permission denied messages

In this above example, I do not have read permission for vmware-root and orbit-Debian-gdm directories. To to avoid this problem try the following syntax:

Sample outputs without permission denied spam from find command:

How does it works?

The 2>/dev/null at the end of the find command tells your shell to redirect the error messages (FD #2) to /dev/null, so you don’t have to see them on screen. Use /dev/null to to send any unwanted output from program/command. All data written on a /dev/null special file is discarded by the system. To redirect standard error to /dev/null and store file list to output.txt, type:

Exclude all “permission denied” messages from “find” command on Linux

There is one problem with the following command. It would filter out all error messages created by find command, not just the permission denied ones:

To avoid that try the following find command along with grep command on Linux or Unix-like systems:

In short you should use following syntax to skip “permission denied” errors messages when running find in Linux or Unix-based systems:

To store output to a file run:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Conclusion

You learned how to hide and fix permission denied messages when using the find command on your Linux, Unix, or macOS-based systems. Of course, we can also run the command as sudo when possible but avoid all this mess. Unfortunately, you will not get sudo or root access at all times. Hence, we talked about various methods here. For your ready references, sudo syntax would be as follows:
sudo find /dir/to/search -name «pattern» -action
sudo find / -name «jail.conf» -print
Please see find/bash command man page online or read it by typing the following man command:
man find
man bash
man zsh
man ksh

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Both errors and warning are thrown into stderr is there any way we can identify that the command has a warning in it and not the error ??
Apart from checking the return code !!

Just use sudo (assuming you’re not running it in a script)

Источник

How to resolve permission denied Linux error

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

What is permission denied Linux error?

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:

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

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.

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

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.

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:

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

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:

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

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

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.

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:

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.

Источник

Читайте также:  Livecd reset windows password
Оцените статью