Linux start shell script

Bash Beginner Series #1: Create and Run Your First Bash Shell Script

Take the first step towards shell scripting. Learn what it takes to create a simple bash script and how to run it.

If you have to do it more than once, automate it!

You will often find yourself repeating a single task on Linux over and over again. It may be a simple backup of a directory or it could be cleaning up temporary files or it can even be cloning of a database.

Automating a task is one of the many useful scenarios where you can leverage the power of bash scripting.

Let me show you how to create a simple bash shell script, how to run a bash script and what are the things you must know about shell scripting.

Create and run your first shell script

Let’s first create a new directory named scripts that will host all our bash scripts.

Now inside this ‘scripts directory’, create a new file named hello.sh using the cat command:

Insert the following line in it by typing it in the terminal:

Press Ctrl+D to save the text to the file and come out of the cat command.

You can also use a terminal-based text editor like Vim, Emacs or Nano. If you are using a desktop Linux, you may also use a graphical text editor like Gedit to add the text to this file.

So, basically you are using the echo command to print «Hello World». You can use this command in the terminal directly but in this test, you’ll run this command through a shell script.

Now make the file hello.sh executable by using the chmod command as follows:

And finally, run your first shell script by preceding the hello.sh with your desired shell “bash”:

You’ll see Hello, World! printed on the screen. That was probably the easiest Hello World program you have ever written, right?

Here’s a screenshot of all the steps you saw above:

Читайте также:  Операционная система linux днс

Convert your shell script into bash script

Confused? Don’t be confused just yet. I’ll explain things to you.

Bash which is short for “Bourne-Again shell” is just one type of many available shells in Linux.

A shell is a command line interpreter that accepts and runs commands. If you have ever run any Linux command before, then you have used the shell. When you open a terminal in Linux, you are already running the default shell of your system.

Bash is often the default shell in most Linux distributions. This is why bash is often synonymous to shell.

The shell scripts often have almost the same syntaxes, but they also differ sometimes. For example, array index starts at 1 in Zsh instead of 0 in bash. A script written for Zsh shell won’t work the same in bash if it has arrays.

To avoid unpleasant surprises, you should tell the interpreter that your shell script is written for bash shell. How do you do that? You use shebang!

The SheBang line at the beginning of shell script

The line “#!/bin/bash” is referred to as the shebang line and in some literature, it’s referred to as the hashbang line and that’s because it starts with the two characters hash ‘#’ and bang ‘!’.

When you include the line “#!/bin/bash” at the very top of your script, the system knows that you want to use bash as an interpreter for your script. Thus, you can run the hello.sh script directly now without preceding it with bash.

Adding your shell script to the PATH (so that it can be run from any directory)

You may have noticed that I used ./hello.sh to run the script; you will get an error if you omit the leading ./

[email protected]:~/scripts$ hello.sh hello.sh: command not found

Bash thought that you were trying to run a command named hello.sh. When you run any command on your terminal; they shell looks for that command in a set of directories that are stored in the PATH variable.

You can use echo to view the contents of that PATH variable:

echo $PATH /home/user/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

The colon character (:) separates the path of each of the directories that your shell scans whenever you run a command.

Linux commands like echo, cat etc can be run from anywhere because their executable files are stored in the bin directories. The bin directories are included in the PATH. When you run a command, your system checks the PATH for all the possible places it should look for to find the executable for that command.

Читайте также:  Linux удалить файлы больше

If you want to run your bash script from anywhere, as if it were a regular Linux command, add the location of your shell script to the PATH variable.

First, get the location of your script’s directory (assuming you are in the same directory), use the PWD command:

Use the export command to add your scripts directory to the PATH variable.

export PATH=$PATH:/home/user/scripts

Notice that I have appended the ‘scripts directory’ to the very end to our PATH variable. So that the custom path is searched after the standard directories.

The moment of truth is here; run hello.sh:

[email protected]:~/scripts$ hello.sh Hello, World!

It works! This takes us to the end of this tutorial. I hope you now have some basic idea about shell scripting. You can download the PDF below and practice what you learned with some sample scripting challenges. Their solutions are also provided in case you need hints.

Since I introduced you to PATH variable, stay tuned for the next bash scripting tutorial where I discuss shell variables in detail.

Источник

Запуск скриптов формата SH в Linux

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

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

  1. Запустите «Терминал» удобным для вас образом, например, через меню приложений или горячую клавишу Ctrl + Alt + T. Запуск терминала для ручного создания скрипта формата SH в Linux
  2. Здесь используйте команду sudo nano script.sh , где nano — используемый текстовый редактор, а script.sh — название создаваемого файла. Можно создавать файл, например, через тот же vi или gedit, сути это не изменит, а название элемента тоже меняется по личным предпочтениям пользователя. Команда для запуска текстового редактора перед созданием скрипта формата SH в Linux
  3. Подтвердите это действие, введя пароль от учетной записи суперпользователя, поскольку оно выполняется с аргументом sudo. Подтверждение запуска текстового редактора для создания скрипта формата SH в Linux
  • Откроется новый файл, в который можно вставить строки скрипта. Ниже вы видите стандартный пример, отвечающий за вывод сообщения «Hello world». Если имеется содержимое другого характера, просто вставьте его в консоль, убедившись, что все строки написаны верно. #!/bin/bash
    echo «Hello world» Создание скрипта формата SH в Linux через текстовый редактор
  • После этого можно сохранить настройки, зажав комбинацию клавиш Ctrl + O. Переход к сохранению скрипта формата SH в Linux после его создания
  • Имя файла изменять не нужно, поскольку его мы задали при создании. Просто нажмите на Enter, чтобы завершить сохранение. Выбор названия для скрипта формата SH в Linux после его создания
  • Покиньте текстовый редактор через Ctrl + X. Завершение работы в текстовом редакторе после создания скрипта формата SH в Linux
  • Как видим, ничего сложного в создании собственных скриптов для Bash нет, однако вся особенность заключается в знании кода. Придется либо писать его с нуля самому, либо скопировать готовые решения из свободных источников. После того, как скрипт успешно реализован в файле, можно смело переходить к следующему этапу.

    Читайте также:  Linux file with dot

    Шаг 2: Настройка скрипта для утилиты env

    Этот шаг тоже является не обязательным, однако без него не обойтись пользователям, которые задействуют утилиту env для запуска скрипта. Без предварительной настройки он просто не откроется, поскольку изначально не были получены соответствующие разрешения. Добавляются они через команду sudo chmod ugo+x script.sh , где script.sh — название необходимого файла.

    Команда для предоставления доступа к скрипту SH в Linux перед его запуском

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

    Ввод пароля для подтверждения открытия доступа к скрипту SH в Linux

    Шаг 3: Запуск имеющегося скрипта

    Перейдем к основному шагу, который и заключается в непосредственном запуске имеющегося скрипта. Для начала рассмотрим простую команду, которая имеет вид ./script.sh и отвечает за запуск файла из текущего места расположения. Результат вывода вы видите на приведенном ниже скриншоте. За пример мы взяли созданный ранее сценарий. По тому же принципу можно указать и полный путь к объекту, чтобы строка изменилась, например, на /home/user/script.sh .

    Команда для открытия скрипта SH в Linux из текущей папки

    В Linux имеется системная переменная PATH. В нее входит ряд папок, отвечающих за выполнение самых разнообразных действий. Одна из них называется /usr/local/bin и используется для ручной инсталляции программ. Если вы не желаете постоянно указывать полный путь к скрипту для его активации, просто добавьте его в одну из папок PATH. Для этого используется строка cp script.sh /usr/local/bin/script.sh .

    Команда для перемещения скрипта формата SH в Linux в папку переменной

    После этого запуск будет доступен путем простого ввод названия файла с учетом расширения.

    Запуск скрипта формата SH в Linux после успешного переноса в папку переменной

    Второй метод открытия заключается в одновременном вызове оболочки. Вам следует переместиться в директорию со скриптом и написать bash script.sh . Этот метод хорош тем, что позволяет не вписывать полный путь к объекту или предварительно добавлять его в соответствующие директории PATH.

    Запуск скрипта формата SH в Linux вместе с оболочкой

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

    Источник

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