Linux permission denied при запуске

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

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.

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?

How did you get the program from computer 1 to computer 2? Did you copy the executable or recompile the source code? What is the output of the command “ls -l program_name”?

This seems to be off topic for SO, because it is not about programming but rights management on Linux

I wrote a .sh file. It refused to execute with this error message. I would say this is definitely on-topic for StackOverflow. I’ve nominated for re-opening.

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.

Источник

Ошибка bash permission denied

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

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

Читайте также:  Linux отключить вход пользователя

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

Источник

Unable to execute bash scripts even as root?

That can happen if you have mounted the file system with the «noexec» option. You should remove it.

Also, to know quickly if your filesystem has been mounted with the ‘noexec’ option, use: mount And to remove the ‘noexec’ option, simply delete it from the list of options against the filesystem in the following file: /etc/fstab . Or alternatively add the ‘exec’ option to the end of the options.

The user option can cause this issue, as well. Removing it allowed me to execute the binary in question.

Another possible reason in Ubuntu can be the default file manager behavior. Go to filemanager->edit->prefferences->behavior and check execute on double click

Читайте также:  Linux remount all fstab

Script needs be executable. Use this:

This duplicates another answer from several years back. It’s probably a common beginner problem, but this particular instance of this answer shouldn’t deserve more upvotes than the original, especially since the question already mentions the original OP had already made sure the permissions were correct.

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 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

Use chmod +x ./test.sh this should allow you to run it.

Also, check to see if the directory/filesystem containing the script is nfs-mounted. root won’t run scripts from nfs-mounted locations.

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.

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.

if you are root user and still have that problem,so your shell is broken.i know that because i couldn’t execute many commands of the sh shell(similar to bash) even i tried as root and it said permission denied like your,i couldn’t change the permission.then i tried to copy them to my directory in /data ,change permission and i could use commands again.but when i try to execute the script,it’s no such file or directory.

Источник

Permission denied when running .sh scripts

program exited with code: 126 . This problem always occur when I try to execute my code. What might be the solution?

When I do that it tells me this chmod: cannot access `geany_run_script.sh’: No such file or directory. Should I run it from the terminal or what?

5 Answers 5

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:

To give the file «the_file_name» execute permission (if the file-system allows you with the RW rights):

Читайте также:  Linux bash if file contains

..what’s your working directory ie. what’s the location of your source code file? ..do you have some experience with windows CLI?

@wkhwilo-012, please copy your executable file Area_circumference and paste it (the file path will be pasted) to update your question’s body.

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)

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:

  1. Use the cd command to find the directory with your source code. Use TAB to help you. If you execute ls -lh , you’ll see a list of possible paths to follow and files to execute.
  2. When you’ve find the blocked file execute chmod +x FILENAME (replace FILENAME with the name of your source code file).
  3. If you have multiple blocked files execute chmod +x * to unlock all files in the current directory. Never chmod +x dangerous or insecure files.
  4. Execute ./FILENAME YOUREVENTUALARGUMENTS to execute your executable file.
  5. Remember that if your compiled program tries to read/write outside your home directory you’ll need to execute it as root by using sudo ./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.

Источник

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