Run bin script linux

How To Run Bash Script In Linux?

The true power of a Bash script is utilized when it is run. But how to do that? Well, there are a plethora of ways to run a Bash script( shell script). Some of them may be useful in certain conditions, while it doesn’t matter how you run the script. Bash scripts are usually executed in the terminal or command-line interface.

To run a Bash script there are many ways. Some of them are given below:

  1. Using bash or sh.
  2. Using source.
  3. Running directly in a bash environment.

For making some of these methods work, the script must have a shebang as the header to indicate it’s a shell script or bash script in this case. So, be sure to include the command below at the top of the file.

This command will make the script run under the bash interpreter. It is recommended to write the shebang header even if it works without them.

Using bash or sh

This is the most standard way of executing the bash script. You must have git bash installed if you are using Windows. For Linux and macOS, bash is installed by default. In this method, we type bash followed by the file name with extension i.e. sh in this case. In a terminal, run the following code by replacing the filename with your bash script filename.

Here, bash is a program that contains the shell environments necessary to run the script from the bash shell. So this will execute the script from the bash interpreter.

Using bash command to run the script.

We can also use sh to run the script as it will direct to the default shell in the setup environment.

Using the sh command to run the bash script.

From the above example, we were able to run a bash script using bash as well as the sh command. If you are not in the same folder/directory as the script, make sure you specify the relative path to the script.

Using source

This method is quite easy to run a bash script, and all of them are quite simple. We just need to type in “source” before the file/script name with an extension. In a terminal, run the following code by replacing the filename with your bash script filename.

The script will simply get executed after “sourcing” the file. The source command will execute the shell script as the default bash command provided you are in the bash shell. You need to be in the bash shell to execute the script using the source command.

Using Source to run a bash script

From the screenshot of the script running, we can see that the source works exactly like the bash or sh command. The above script is a very basic script, but that doesn’t matter as long as the script is errorless and bug-free. Also, you need to add the relative path here as well if you are not in the same directory as the bash script.

Читайте также:  At команды через консоль linux

By specifying the path to the script and chmod

This is a standalone method to run a bash script. We have to execute the script as an executable, we can run the script anywhere provided we have a bash shell somewhere in the environment. To make it executable we need to make sure we have the rights to run the file as an executable. We will use chmod for changing the rights on the file/script. In a terminal, run the following code by replacing the filename with your bash script filename.

The above command will allow us to execute the file. So it changes the mode of the file, the file should be read-only, executable, or any other mode for files. If you are using Linux and are not the root user, simply use sudo before the command chmod. The +x command will make sure the file is executable by everyone in the environment.

After the permission of the file is taken care of, we can now simply execute the file as follows. The command below takes into consideration that you are in the same directory as the file/ bash script is in.

If you are not on the same path as the bash script, make sure you provide the relative path to the file or the bash script.

using chmod and executing the script.

Executing a script from a relative path.

The above snippets and screenshots show that we can run the scripts in a bash environment by changing the mode of the file using the chmod.

From the following guide, we were able to run scripts in Linux using various methods and programs. So, those were some methods to run a bash script on Linux or pretty much anywhere.

Источник

How to Run a Shell Script in Linux [Essentials Explained for Beginners]

Here are all the essential details you should know about executing a shell script in the Linux command line.

That maybe simple, but it doesn’t explain a lot. Don’t worry, I’ll do the necessary explaining with examples so that you understand why a particular syntax is used in the given format while running a shell script. I am going to use this one line shell script to make things as uncomplicated as possible:

[email protected]:~/Scripts$ cat hello.sh echo "Hello World!"

Method 1: Running a shell script by passing the file as argument to shell

The first method involves passing the script file name as an argument to the shell. Considering that bash is the default shell, you can run a script like this:

Do you know the advantage of this approach? Your script doesn’t need to have the execute permission. Pretty handy for quick and simple tasks. Run A Shell Script LinuxIf you are not familiar already, I advise you to read my detailed guide on file permission in Linux. Keep in mind that it needs to be a shell script that you pass as argument. A shell script is composed of commands. If you use a normal text file, it will complain about incorrect commands. Running Text File As Script in LinuxIn this approach, you explicitly specified that you want to use bash as the interpreter for the script. Shell is just a program and bash is an implementation of that. There are other such shells program like ksh, zsh, etc. If you have other shells installed, you can use that as well instead of bash. For example, I installed zsh and used it to run the same script: Execute Shell Script With Zsh

Читайте также:  Линукс для мощного пк

Method 2: Execute shell script by specifying its path

The other method to run a shell script is by providing its path. But for that to be possible, your file must be executable. Otherwise, you’ll have “permission denied” error when you try to execute the script. So first you need to make sure that your script has the execute permission. You can use the chmod command to give yourself this permission like this:

Once your script is executable, all you need to do is to type the file name along with its absolute or relative path. Most often you are in the same directory so you just use it like this:

Running Shell Script In Other Directory

If you are not in the same directory as your script, you can specify it the absolute or relative path to the script:

That ./ before the script is important (when you are in the same directory as the script)

Executing Shell Scripts Linux

Why can you not use the script name when you are in the same directory? That is because your Linux systems looks for the executables to run in a few selected directories that are specified in the PATH variable. Here’s the value of PATH variable for my system:

[email protected]:~$ echo $PATH /home/abhishek/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
  • /home/abhishek/.local/bin
  • /usr/local/sbin
  • /usr/local/bin
  • /usr/sbin
  • /usr/bin
  • /sbin
  • /bin
  • /usr/games
  • /usr/local/games
  • /snap/bin

The binaries or executable files for Linux commands like ls, cat etc are located in one of those directories. This is why you are able to run these commands from anywhere on your system just by using their names. See, the ls command is located in /usr/bin directory.

Locating Command Linux

When you specify the script WITHOUT the absolute or relative path, it cannot find it in the directories mentioned in the PATH variable.

Why most shell scripts contain #! /bin/bash at the beginning of the shell scripts?

Remember how I mentioned that shell is just a program and there are different implementations of shells.

When you use the #! /bin/bash, you are specifying that the script is to run with bash as interpreter. If you don’t do that and run a script in ./script.sh manner, it is usually run with whatever shell you are running.

Does it matter? It could. See, most of the shell syntax is common in all kind of shell but some might differ.

For example, the array behavior is different in bash and zsh shells. In zsh, the array index starts at 1 instead of 0.

Bash Vs Zsh

Using #! /bin/bash indicates that the script is bash shell script and should be run with bash as interpreter irrespective of the shell which is being used on the system. If you are using zsh specific syntax, you can indicate that it is zsh script by adding #! /bin/zsh as the first line of the script.

The space between #! /bin/bash doesn’t matter. You can also use #!/bin/bash.

Was it helpful?

I hope this article added to your Linux knowledge. If you still have questions or suggestions, please leave a comment.

Expert users can still nitpick this article about things I missed out. But the problem with such beginner topics is that it is not easy to find the right balance of information and avoid having too much or too few details.

If you are interested in learning bash script, we have an entire Bash Beginner Series on our sysadmin focused website Linux Handbook.

If you want, you may also purchase the ebook with additional exercises to support Linux Handbook.

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

Мы разрешаем выполнять запуск 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.

Источник

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