Running bash script in 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:

Читайте также:  Open home directory linux

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

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

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

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

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

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

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

Выводы

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

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

Источник

How to run a shell script on Linux

what is bash shell,

O ne of the most powerful utilities you can use when working with Linux systems is the terminal. Here, you can execute any commands to perform any tasks you might think of – launching an application, installing/ uninstalling applications, creating and deleting files/ directories, etc. However, most users well versed with Linux systems utilize the Terminal to carry out one more task – writing and running shell scripts.

What is a shell script?

A shell script is a simple program that runs on the Unix/ Linux shell. There are different types of Shells, as you will see in the next section. A Unix/ Linux shell program interprets user commands which are either directly entered by the user or which can be read from a file that we now call a shell script. It is important to note that shell scripts are interpreted and not compiled. Therefore, when you write a script on your system, you don’t need to compile it. Just make it executable and execute it.

    A script to install an application. That is mainly used in applications that require you to install additional libraries/ dependencies. The developers write a simple script that does all the dirty work to relieve the end-user of this hassle.

The examples listed above might sound relatively easy to implement. However, there are complex scripts that perform complicated tasks like:

Let’s look at the different types of Shells.

Читайте также:  Kaspersky endpoint security linux gui

Types of shells

The sh shell

The Sh shell, commonly known as Secure Shell, was one of the earliest Shell included in the Unix/ Linux systems. That was the shell logged in by the superuser known as root. The root user could use this shell to create and delete users on the system.

The C shell (Csh)

You will undoubtedly run into the C-shell if you are a network or systems administrator working in a Linux or Unix environment. Therefore, it’s highly advisable to get familiar with this shell type. Casual users and developers will likely suggest using other shells, but the C-shell is an excellent choice if you are comfortable with the C programming language.

The Korn shell (Ksh)

The Korn shell is the one you can use interactively to execute commands from the command line or programmatically to create scripts that can automate many computer maintenance and system administration tasks.

The Bourne Again Shell (Bash)

The Bash shell is a far too big subject to be covered in a few lines. However, it’s one of the most commonly used scripting languages that you will find today, and most of the content you will find around shell scripting will be in Bash. We highly recommend learning Bash de to its versatility and ease of use.

This post will focus on Bash scripting, and the Linux distribution we will use to run the scripts is Ubuntu 20.04 LTS.

Understanding the various components of a shell script (Bash)

The first step to writing any Bash script is understanding the file extension you will use. Bash uses the ‘.sh’ file extension. Therefore, if I had a script called ‘script_one,’ I would save it as ‘ script_one.sh .’ Luckily, Bash allows you to run scripts even without the ‘.sh’ extension.

The next thing you need to understand is the Shebang line, a combination of ‘ bash # ‘ and ‘ bang ! followed by the bash shell path. The shebang line is written at the start of every script and specifies the path to the program to run the script (it’s a path to the bash interpreter). Below is an example of the Shebang line.

However, you might have seen other people writing is as:

You might have noticed the difference in the path – one uses the /usr/bash while the other uses /usr/bin/bash . To get the bash path on your system, execute the command below.

In our case, it’s /usr/bin/bash

get bash path

Writing our first shell script

Now that you understand Shell scripts, the different Linux Shells available, and the Shebang line, let’s write our first Bash script.

1. Write and run Bash scripts from Terminal

Below is a script that prints the name “hello world,” current time, and the hostname of our system. In our case, we used the nano editor to write the script. Execute the command below.

Читайте также:  Linux перестает работать wifi

Copy and paste the lines of code below. If you have a good understanding of Bash, you can add your lines of code. When done, save the file (Ctrl + S) and exit (Ctrl + X).

#! /usr/bin/bash echo "Hello World!" echo echo "Hostname is set to : $HOSTNAME" now=$(date +"%r") echo "Current time : $now" echo

Of course, this is a simple script, but it’s enough for us to understand how to run Bash scripts on Linux systems.

To get started, make the script executable by executing the chmod command using the syntax below.

chmod +x [script-name] e.g chmod +x script_one.sh

An additional exciting feature to note with Bash scripts is that they will have a different color from other scripts and files if the script is executable. See the image below.

simple bash script

To run our script from the Terminal, use the syntax below.

./[script-name] e.g. ./script_one.sh

run bash script

That’s it! You have successfully run your first Bash script from the Terminal. Now let’s look at how you can create and run a script from the Graphical User Interface (GUI).

2. Create and run Bash scripts from the GUI

If you prefer working from the GUI, follow the steps below. Unfortunately, you will still have to interact with the Terminal at one point or another.

Launch your favorite code editor (Gedit, mousepad, etc.) and write your script. You can paste the code below for a test.

#! /usr/bin/bash echo "Hello World!" echo echo "Hostname is set to : $HOSTNAME" now=$(date +"%r") echo "Current time : $now" echo

bash script on gedit

Save the file and remember to add the ‘.sh’ extension. Right-click on the bash file and select properties to make the script executable. Select the ‘Permissions’ tab and tick the checkbox next to the “Allow executing file as a program” option. See the image below.

make script executable

Now, when you double-click on the script file, you will see an option to run the file on the Terminal. Select “Run in Terminal,” and the script will execute on the Terminal.

That’s it! You have successfully created and run a script from your graphical user interface.

Conclusion

This post has given you a step-by-step guide on running a shell script on Linux. We have looked at both Terminal and GUI methods. However, we highly recommend running the script from the Terminal, which is much more versatile and will also help you get much more familiar with working with remote systems which only give you command-line access. If you are only getting started with Bash scripting, the posts below might come in quite handy.

Источник

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