Writing script in linux

Writing Our First Script and Getting It to Work

To successfully write a shell script, we have to do three things:

  1. Write a script
  2. Give the shell permission to execute it
  3. Put it somewhere the shell can find it

Writing a Script

A shell script is a file that contains ASCII text. To create a shell script, we use a text editor. A text editor is a program, like a word processor, that reads and writes ASCII text files. There are many, many text editors available for Linux systems, both for the command line and GUI environments. Here is a list of some common ones:

Name Description Interface
vi, vim The granddaddy of Unix text editors, vi , is infamous for its obtuse user interface. On the bright side, vi is powerful, lightweight, and fast. Learning vi is a Unix rite of passage, since it is universally available on Unix-like systems. On most Linux distributions, an enhanced version of vi called vim is provided in place of vi. vim is a remarkable editor and well worth taking the time to learn it. command line
Emacs The true giant in the world of text editors is Emacs originally written by Richard Stallman. Emacs contains (or can be made to contain) every feature ever conceived of for a text editor. It should be noted that vi and Emacs fans fight bitter religious wars over which is better. command line
nano nano is a free clone of the text editor supplied with the pine email program. nano is very easy to use but is very short on features compared to vim and emacs . nano is recommended for first-time users who need a command line editor. command line
gedit gedit is the editor supplied with the GNOME desktop environment. gedit is easy to use and contains enough features to be a good beginners-level editor. graphical
kwrite kwrite is the «advanced editor» supplied with KDE. It has syntax highlighting, a helpful feature for programmers and script writers. graphical

Let’s fire up our text editor and type in our first script as follows:

Clever readers will have figured out how to copy and paste the text into the text editor 😉

This is a traditional «Hello World» program. Forms of this program appear in almost introductory programming book. We’ll save the file with some descriptive name. How about hello_world ?

The first line of the script is important. It is a special construct, called a shebang, given to the system indicating what program is to be used to interpret the script. In this case, /bin/bash . Other scripting languages such as Perl, awk, tcl, Tk, and python also use this mechanism.

The second line is a comment. Everything that appears after a «#» symbol is ignored by bash . As our scripts become bigger and more complicated, comments become vital. They are used by programmers to explain what is going on so that others can figure it out. The last line is the echo command. This command simply prints its arguments on the display.

Setting Permissions

The next thing we have to do is give the shell permission to execute our script. This is done with the chmod command as follows:

The «755» will give us read, write, and execute permission. Everybody else will get only read and execute permission. To make the script private, (i.e., only we can read and execute), use «700» instead.

Putting It in Our Path

At this point, our script will run. Try this:

We should see «Hello World!» displayed.

Before we go any further, we need to talk about paths. When we type the name of a command, the system does not search the entire computer to find where the program is located. That would take a long time. We see that we don’t usually have to specify a complete path name to the program we want to run, the shell just seems to know.

Well, that’s correct. The shell does know. Here’s how: the shell maintains a list of directories where executable files (programs) are kept, and only searches the directories on that list. If it does not find the program after searching each directory on the list, it will issue the famous command not found error message.

This list of directories is called our path. We can view the list of directories with the following command:

This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is entered. In our first attempt to execute our new script, we specified a pathname («./») to the file.

We can add directories to our path with the following command, where directory is the name of the directory we want to add:

Читайте также:  Вкладки для windows explorer

A better way would be to edit our .bash_profile file to include the above command. That way, it would be done automatically every time we log in.

Most Linux distributions encourage a practice in which each user has a specific directory for the programs he/she personally uses. This directory is called bin and is a subdirectory of our home directory. If we do not already have one, we can create it with the following command:

If we move our script into our new bin directory we’ll be all set. Now we just have to type:

and our script will run. On some distributions, most notably Ubuntu (and other Debian-based distributions), we will need to open a new terminal session before our newly created bin directory will be recognized.

© 2000-2021, William E. Shotts, Jr. Verbatim copying and distribution of this entire article is permitted in any medium, provided this copyright notice is preserved.

Linux® is a registered trademark of Linus Torvalds.

Источник

ИТ База знаний

Курс по Asterisk

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

Учимся писать базовые скрипты в Unix и Linux

Если вы еще не умеете писать скрипты в системах Unix и Linux, эта статья познакомит с основами написания скриптов.

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

Онлайн курс по Linux

Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps

Идентификация оболочки.

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

Bash является одной из самых популярных оболочек, но существуют также zsh , csh , tcsh и korn . Есть даже оболочка под названием fish , которая может быть особенно полезна новичкам в Linux благодаря полезным параметрам автозаполнения команд. Чтобы определить, какую оболочку вы используете, используйте эту команду:

Вы также можете определить свою основную оболочку, просмотрев файл /etc/passwd :

Один из способов определить, какие оболочки доступны в системе Linux, — это проверить файл /etc/shells .

На выводе видно, что доступно всего девять оболочек.

Какую оболочку выбрать пользователю во многом зависит от того, что он привык использовать, поскольку большая часть синтаксиса в скриптах не представляет команды, которые вы найдете в /bin , /us /bin или /usr/local/bin . Вместо этого они являются частью самой оболочки и называются «встроенными». Сюда входят команды, используемые для цикла (например, for и while ).

Один из простых вариантов создания скриптов — использовать ту оболочку, которую вы используете в командной строке, поскольку, в конце концов, вам будет более или менее комфортно ее пользоваться.

Выбор оболочки

Чтобы определить, какая из доступных оболочек будет выполнять команды вашего скрипта, в первой строке вашего скрипта пропишите одну из строчек, приведенных ниже:

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

Выполнение команд

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

Чтобы запустить этот скрипт, выполните команду:

Добавление комментариев

Рекомендуется добавлять к скриптам комментарии, объясняющие, для чего предназначен скрипт, особенно если скрипт длинный или имеется сложный синтаксис. Просто начните комментарий со знака # . Комментарии могут быть отдельными строками или добавляться в конец команд в скрипте. Например:

Делаем файл исполняемым

Чтобы сделать скрипт исполняемым, используйте команду chmod и убедитесь, что предполагаемые пользователи могут его запустить. Например:

Если скрипт не сделан как исполняемый, его все равно можно запустить с помощью символа . Это встроенная функция, которая «выполняет» (т. е. читает и запускает) скрипт.

Использование команды if

Команда if позволяет вам проверять условия или переменные. В примере ниже мы проверяем, запускается ли скрипт в пятницу.

Базовый синтаксис команды if — if value == other_value . Знак == выполняет сравнение, и необходимо убедиться, что оболочка видит по одному значению с каждой стороны оператора сравнения. По этой причине часто приходится заключать свои строки в кавычки.

Понятие переменных

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

Запрос пользователя на ввод данных

Чтобы пользователь, во время исполнения скрипта, смог ввести некоторую информацию, вам необходимо вывести как подсказку, так и команду, чтобы прочитать, что вводит пользователь. Вы также должны присвоить переменной имя, которое имеет смысловое значение, как в этом примере. Обратите внимание, что использование команды echo -n означает, что пользователь вводит свой ответ в той же строке, что и приглашение.

Читайте также:  Не удаляется поврежденная папка с компьютера windows 10

Человек, запускающий сценарий, увидит приглашение и введет ответ :

Использование аргументов командной строки

Чтобы использовать аргументы, которые пользователь вводит вместе с именем скрипта, необходимо знать, как их идентифицировать. Аргументам скрипта будут присвоены имена $1 , $2 и так далее. Для любого аргумента, который вы собираетесь использовать неоднократно, вы можете рассмотреть возможность присвоения этих значений более значимым именам переменных.

В этом случае мы проверяем, является ли первый предоставленный аргумент числовым, и закрываем скрипт, если это не так. Если ответ — число, то далее назначаем его переменной $loops , чтобы использовать позже в скрипте.

Еще одна полезная вещь, которую нужно сделать в скрипте, — это сначала проверить наличие аргументов. В противном случае синтаксис, подобный показанному выше, не сработает, потому что оболочка увидит выражение if [[! = 4 *]]; , что приведет к синтаксической ошибке.

Чтобы проверить правильность количества предоставленных аргументов, вы можете использовать синтаксис, подобный приведенному ниже, который проверяет, были ли предоставлены по крайней мере два аргумента, и, в противном случае, напоминает пользователю, что требуется как количество строк, так и имя файла:

Различные способы создания циклов

Есть несколько способов сделать цикл внутри скрипта. Используйте for , если вы хотите повторить действие заданное количество раз. Например:

Используйте while , если хотите выполнять какое-то действие, пока условие существует или не существует.

Использование оператора case

Операторы case позволяют вашим скриптам реагировать по-разному в зависимости от того, какие значения проверяются. В приведенном ниже скрипте используются разные команды для извлечения содержимого файла, предоставленного в качестве аргумента, путем определения типа файла.

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

Реакция на ошибки

Вы можете обнаруживать ошибки в скриптах и реагировать на них и тем самым избегать других ошибок. Хитрость заключается в том, чтобы проверять выходные коды после запуска команд. Если код выхода имеет значение, отличное от нуля, произошла ошибка. В этом скрипте проверяется, запущен ли Apache, но отправляем результат проверки в /dev/null . Затем проверяем, не равен ли код выхода нулю, поскольку это означает, что команда ps не получила ответа. Если код выхода не равен нулю, сценарий сообщает пользователю, что Apache не запущен.

Онлайн курс по Linux

Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps

Источник

The Beginner’s Guide to Scripting on Linux

Have you ever wanted to learn “scripting” in Linux? Making them is easier than you might think. Sometimes scripts (often referred to as shell or bash scripts) are real programs with complicated code inside. Other times they’re just a long list of tasks that users put together to make getting things done under Linux faster and easier.

In this article we’ve decided to make a quick guide explaining how to make a basic shell script under Linux. This tutorial won’t turn you into a Bash or scripting expert. Instead, it will show you how easy it is to get started (and the best practices) scripting in Linux.

Why would you make a script?

Making scripts in Linux is a very useful skill to have. Even if you don’t fully understand Bash, you can use your limited knowledge of the terminal to automate and “mass-accomplish” some tasks, or simply to open multiple applications simultaneously.

For example: maybe you just built Arch Linux from scratch. The operating system is installed, along with all of the basic packages, and it can boot to the terminal when the operating system starts up. Arch Linux takes time to set up, so the process isn’t completed.

It is at this point where the user could write a Bash script and accomplish everything at once. None of this is programming, or advanced for that matter. However, given the fact that the user understands enough about the way Arch Linux works, they’d be able to automate almost the entire post-setup process (desktop environment, drivers, user setup, etc.).

The only limit to your bash script is your own Linux and Bash knowledge! Making them is easier than you might think.

Getting started – Shebangs

When writing code, things need to be specified and resources loaded. When scripting with the shell, some things need to be specified as well. In bash scripting this is known as a “shebang.” The shebangs used in scripts tells the script what interpreter it should execute under. This could be Bash or any other scripts available in your system. Do note that different languages have their own shebangs.

For example: When writing a Python script, the shebang would be #!/usr/bin/python , etc.

Bash has many different shebangs that can be used, but most users have probably only seen the #!/bin/bash one. As a general rule, use #!/bin/bash when writing a simple script and don’t plan on taking it off of Linux. All modern Linux distributions are on the same version of bash, and the bash shell is usually located in the same place.

Another shebang that proves itself useful is the #!/usr/bin/env bash shebang. This one is designed for portability and should be used if the script is designed to run on other Unix-like operating systems (BSDs, macOS, etc.).

Читайте также:  Сброс пароля администратора домена windows server 2016

Best Practices

Writing scripts in Bash can be a complicated process if the writer makes it that way. More often than not, scripts are just a collection of different operations. Moving a file, downloading something, installing programs, and that sort of thing.

  • Keep in mind that Bash is a language that is designed to manipulate files and processes on the system. If Bash meets your needs, that is good. However, do understand that for advanced programming, Bash really isn’t the right choice, and it’d be best to move onto something like Python.
  • Make your scripts “SH” compatible and in the “.sh” format if the plan is to use scripts on more than just a Linux platform. Though other UNIX-like operating systems may have “bash-like” shells, some don’t have bash at all, and it’s good to be prepared for this.
  • Learn the Bash shell and how it works. It’ll help you write your scripts better.
  • Always use a shebang and more importantly: use the right one. It can mean the difference between a good script and a terrible one that doesn’t work right.
  • Always comment out every operation. In six months you might come back to your script and wonder what everything means, so it is crucial that your script is documented well and easy to understand (for you and anyone else who might see it).
  • Make your code readable. Even if your script isn’t anything complex, it should still make sense, and making them is easier than you might think.
  • Test your script for errors before giving it out to others. Don’t make others bug test for you. Ideally, scripts should work before you send them out for people to use.

Making a script

To start scripting, all you need is a text editor. Any simple text editor will do – it doesn’t have to be a complicated or comprehensive one. For this example we’ll make a simple Ubuntu update script using Gedit.

This first part of the script is the shebang, like mentioned before. This allows the script to tell the interpreter what it should use to understand the code.

Next, let’s write a comment. This will allow anyone who uses the script to understand what the code is meant to do. Comments can be added to a script by placing a “#” symbol. Anything after it won’t be picked up by the script.

Now it is time to add the code to the script. In this case we’re working on making a bash script that will run Ubuntu’s two update commands in succession. Start off with the update software sources command.

The second part of the script is the apt upgrade command. This command allows the previously checked updates to be installed. Add a -y to the end so that the script won’t need any user interaction. This will allow the command to update by itself.

Save the script with a “.sh” extension. For example, “myscript.sh.”

To run the script, open a terminal and type:

This will mark the newly created script as executable. Doing this to scripts isn’t always required, as for the most part Bash will run it anyways. Regardless, this a good practice when scripting.

To execute the newly created script, run the following command:

File Extensions

There isn’t a difference in file extensions for scripts. Naming a file with the “.sh” file extension does little to affect the way the “program” runs. A Bash script will still run with no file extension – blank text files and everything in between as long as the right commands and arguments are present.

Even though the Bash shell ignores file extensions, that doesn’t mean the script writer should. Some desktop environments that allow for setting shell scripts to run at startup depend on the script to have the correct “.sh” file extension. This also helps for organization purposes, too.

When it comes down to it, most shell scripts are saved as “.sh” files for portability. The “sh” doesn’t have anything to do with Bash itself, and the script can run with any compatible shell.

Alternatively, scripts can be saved as .bash, .ksh (Unix korn shell), etc. These file extensions are inferior and really limit the usefulness of a script. This is due to the fact that they are designed only for the shells that use those extensions.

Code resources

For those looking for useful Bash scripts, check out the Bash User Repository on Reddit. It is a collection of neat and useful scripts that are free to use and modify!

Additionally, those looking to learn the advanced nature of Bash and programming with the shell should check out Freecode. The website has an entire lesson guide that teaches everything there is to know about advanced Bash scripting.

Conclusion

Though scripting with Bash on Linux isn’t a unique feature (Macs have bash too), it tends to help Linux users out more overall. Considering so much of Linux can be accomplished under the terminal, learning how to manipulate the shell is very useful.

What Bash scripts do you use under Linux to make your life easier? Tell us below!

Derrik Diener is a freelance technology blogger.

Источник

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