Linux права выполнение скрипта

Запуск скрипта sh в Linux

Вся сила Linux в использовании терминала. Это такая командная оболочка, где вы можете выполнять различные команды, которые будут быстро и эффективно выполнять различные действия. Ну впрочем, вы наверное это уже знаете. Для Linux было создано множество скриптов, которые выполняются в различных командных оболочках. Это очень удобно, вы просто объединяете несколько команд, которые выполняют определенное действие, а затем выполняете их одной командой или даже с помощью ярлыка.

Но у новичков может возникнуть вопрос — как запустить скрипт в Linux, что для этого нужно сделать, что будет происходить и какие команды нужно выполнить. Но сначала нужно рассмотреть как работают скрипты и что такое исполняемость.

Как работают скрипты

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

Теперь о том, как работают скрипты. Это обычные файлы, которые содержат текст. Но если для них установлен атрибут исполняемости, то для их открытия используется специальная программа — интерпретатор, например, оболочка bash. А уже интерпретатор читает последовательно строку за строкой и выполняет все команды, которые содержатся в файле. У нас есть несколько способов выполнить запуск скрипта linux. Мы можем запустить его как любую другую программу через терминал или же запустить оболочку и сообщить ей какой файл нужно выполнять. В этом случае не нужно даже флага исполняемости.

Запуск скрипта sh в Linux

Сначала рассмотрим пример небольшого sh скрипта:

Вторая строка — это действие, которое выполняет скрипт, но нас больше всего интересует первая — это оболочка, с помощью которого его нужно выполнить. Это может быть не только /bin/bash, но и /bin/sh, и даже /usr/bin/python или /usr/bin/php. Также часто встречается ситуация, что путь к исполняемому файлу оболочки получают с помощью утилиты env: /usr/bin/env php и так далее. Чтобы выполнить скрипт в указанной оболочке, нужно установить для него флаг исполняемости:

Читайте также:  Gre туннель linux ubuntu

Мы разрешаем выполнять запуск sh linux всем категориям пользователей — владельцу, группе файла и остальным. Следующий важный момент — это то место где находится скрипт, если вы просто наберете script.sh, то поиск будет выполнен только глобально, в каталогах, которые записаны в переменную PATH и даже если вы находитесь сейчас в той папке где находится скрипт, то он не будет найден. К нему нужно указывать полный путь, например, для той же текущей папки. Запуск скрипта sh в linux:

Если вы не хотите писать полный путь к скрипту, это можно сделать, достаточно переместить скрипт в одну из папок, которые указаны в переменной PATH. Одна из них, которая предназначена для ручной установки программ — /usr/local/bin.

cp script.sh /usr/local/bin/script.sh

Теперь вы можете выполнить:

Это был первый способ вызвать скрипт, но есть еще один — мы можем запустить оболочку и сразу же передать ей скрипт, который нужно выполнить. Вы могли редко видеть такой способ с bash, но он довольно часто используется для скриптов php или python. Запустим так наш скрипт:

А если нам нужно запустить скрипт на php, то выполните:

Вот так все просто здесь работает. Так можно запустить скрипт как фоновый процесс, используйте символ &:

Даже запустить процесс linux не так сложно.

Выводы

Как видите, запуск скрипта sh в linux — это довольно простая задача, даже если вы еще плохо знакомы с терминалом. Существует действительно много скриптов и некоторые из них вам возможно придется выполнять. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

getting permission to execute a bash script

This fails returning i don’t have permission to execute it, sudo exec isn’t a thing so i do sudo -i then run exec /var/www/script as root and i still have permission denied. I fairly uncertain why executing it as root doesn’t work. Im wondering if i’m A) using the wrong command to execute a bash script
B) have incorrect formatting in the script
C) shouldn’t have saved it to /var/www/
D) done some other thing that i’m not even aware of. Im running ubuntu server 16.04 if that helps.

Читайте также:  Linux mp4 to wmv

2 Answers 2

File Permissions

First, make sure that you have the correct file permissions:

chmod +x /var/www/script_name #Gives the current user execute permissions 

Executing Your Bash Script

In order to execute your bash script, the easiest option is to just simply call it (without any additional commands) by typing in the relative path to the script:

There are other options for explicitly executing your script from the shell (in your case, use the bash shell to execute your script as a bash script). From TLDP documentation.

A script can also explicitly be executed by a given shell, but generally we only do this if we want to obtain special behavior, such as checking if the script works with another shell or printing traces for debugging:

rbash script_name.sh # Execute using the restricted bash shell sh script_name.sh # Execute using the sh shell bash -x script_name.sh # Execute using the bash shell 

A Note on File Extensions: «Shebang» line > File extension

It is not an advised practice to use file extensions with your scripts, especially if you think your code may evolve beyond its current functionality.

Just in case you were wondering if the file extension may be your problem. it is not. It is important that you know that the file extension of a script isn’t necessary at all. What matter is what you put in the «shebang» line:

It won’t matter what file extension you use — the «shebang» line indicates what shell will be used to execute the script. You could save a script with the «shebang» of #!/bin/bash as script_name.py , but it would remain a bash script. If you attempt to execute it, ./script_name.py , it would be executed as a bash script.

As @Arjan mentioned in the comments, using file extensions for your script could lead to unnecessary complications if you decide to change the implementation of your project (i.e., a different shell / language):

I could decide later to shift my project to sh , python , perl , C , etc. Perhaps because I want to add functionality. Perhaps because I want to make it portable to a system without bash . It would be much more difficult if I used the .sh file extension, since then I’d need to change all my references to the script just because I changed its implementation.

Источник

Читайте также:  How to update libreoffice linux

How to Make Bash Script Executable Using Chmod

chmod executable

In this tutorial, I am going through the steps to create a bash script and make the script executable using the chmod command. After that, you will be able to run it without using the sh or bash commands.

Step 1: Creating a Bash File

The first step is to create a new text file with .sh extension using the following command.

Step 2: Writing a Sample Script

Open the newly created file using any of your favorite editors to add the following bash script to the file.

$ vim hello_script.sh #!/bin/bash echo "Hello World"

Save and close the file using ESC +:wq!

Step 3: Executing the Bash Script

There are two ways to run the bash file. The first one is by using the bash command and the other is by setting the execute permission to bash file.

Let’s run the following command to execute the bash script using bash or sh command.

Execute the bash script

Step 4: Set Executable Permissions to Script

The second way to execute a bash script is by setting up the executable permissions.

To make a script executable for the owner of the file, use u+x filename.

To make the file executable for all users use +x filename or a+x filename.

Step 5: Running Executable Script

After you have assigned the executable permissions to the script, you can run the script without bash command as shown.

Running a executable script

Another Example

In the following example, I am going to write and execute a bash script to take a backup from source to destination.

$ vim backup_script.sh #!/bin/bash TIME=`date +%b-%d-%y` DESTINATION=/home/ubuntu/backup-$BACKUPTIME.tar.gz SOURCE=/data_folder tar -cpzf $DESTINATION $SOURCE

Save and close the file using :wq! and give it the executable permissions for all users using the following command:

bash example script and execute

Conclusion

At the end of this tutorial, you should be familiar with how to set a script executable in Linux.

I hope you enjoyed reading it, please leave your suggestion in the below command section.

If this resource helped you, let us know your care by a Thanks Tweet. Tweet a thanks

Источник

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