- How to Create Simple Shell Scripts in Linux
- 1. Create a Simple Shell Script
- 2. Using Conditional Statements to Execute Code
- Example of an if Statement Only
- Example of an if-else Statement
- Example of an if-elif-else Statement
- 3. Using the If Statement with AND Logic
- 5. Using the If Statement with OR Logic
- Use Looping Constructs
- While loop
- For loop
- Bash Positional Parameters
- Shell Command Exit Codes
- Processing Output of Shell Commands within a Script
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- Учимся писать базовые скрипты в Unix и Linux
- Идентификация оболочки.
- Выбор оболочки
- Выполнение команд
- Добавление комментариев
- Делаем файл исполняемым
- Использование команды if
- Понятие переменных
- Запрос пользователя на ввод данных
- Использование аргументов командной строки
- Различные способы создания циклов
- Использование оператора case
- Реакция на ошибки
How to Create Simple Shell Scripts in Linux
Creating shell scripts is one of the most essential skills that Linux users should have at the tip of their fingers. Shell scripts play an enormous role in automating repetitive tasks which otherwise would be tedious executing line by line.
In this tutorial, we highlight some of the basic shell scripting operations that every Linux user should have.
1. Create a Simple Shell Script
A shell script is a file that comprises ASCII text. We will start by creating a simple shell script, and to do this, we will use a text editor. There are quite a number of text editors, both command-line and GUI-based. For this guide, we will use the vim editor.
We will start off by creating a simple script that displays “Hello world” when executed.
Paste the following content in the file and save.
Let’s go over the shell script line by line.
- The first line – #!/bin/bash – is known as the shebang header. This is a special construct that indicates what program will be used to interpret the script. In this case, this will be the bash shell indicated by /bin/bash. There are other scripting languages such as Python which is denoted by #!/usr/bin/python3 and Perl whose shebang header is is denoted by #!/usr/bin/perl .
- The second line is a comment. A comment is a statement that describes what a shell script does and is not executed when the script is run. Comments are always preceded by the hash sign # .
- The last line is the command that prints the ‘Hello World’ message on the terminal.
The next step is to make the script executable by assigning execute permission using the chmod command as shown.
Finally, run the shell script using either of the commands:
Create Hello World Shell Script
2. Using Conditional Statements to Execute Code
Like other programming languages, conditional statements are used in bash scripting to make decisions, with only a slight variation in the syntax. We are going to cover the if, if-else, and elif conditional statements.
Example of an if Statement Only
The if statement can be used to test single or multiple conditions. We will start off with the fundamental use of the if statement to test a single condition. The if statement is defined by the if . fi blocks.
Let’s take a look at the shell script below.
The above shell script prompts the user to provide a score that is then stored in a variable x. If the score corresponds to 70, the script returns the output “Good job!”. The comparison operator == is used to test if the score entered, which is stored in the variable x, is equivalent to 100.
if Statement in Shell Script
Other comparison operators you can use include:
- -eq – Equal to
- -ne – Not equal to
- -lt – Less than
- -le – Less than or equal to
- -lt – Less than
- -ge – Greater than or equal to
For example, the if-statement block below prints out ‘Work Harder’ if the input score is any value less than 50.
if Statement in Shell Script
Example of an if-else Statement
For situations where you have 2 possible outcomes: – whether this or that – the if-else statement comes in handy.
The script below reads the input score and checks whether it is greater than or equal to 70.
If the score is greater than or equal to 70, you get a ‘Great job, You passed!’ message. However, if the score falls below 70, the output ‘You failed’ will be printed.
if-else statement in Shell Script
Example of an if-elif-else Statement
In scenarios where there are multiple conditions and different outcomes, the if-elif-else statement is used. This statement takes the following format.
For example, we have a script for a lottery that checks if the number entered is either 90, 60 or 30.
if-elif-else statement
3. Using the If Statement with AND Logic
You can use the if statement alongside the AND logic operator to execute a task if two conditions are satisfied. The && operator is used to denote the AND logic.
5. Using the If Statement with OR Logic
When using the OR logic, that is represented by || symbol, either one of the conditions needs to be satisfied with the script to give the expected results.
If statement with OR logic
Use Looping Constructs
Bash loops allow users to perform a series of tasks until a certain result is achieved. This comes in handy in performing repetitive tasks. In this section, we shall have a peek at some of the loops which you’d also find in other programming languages.
While loop
This is one of the easiest loops to work with. The syntax is quite simple:
The while loop below lists all the numbers from 1 to 10 when executed.
Let’s disscuss the while loop:
The variable counter is initialized to 1. And while the variable is less than or equal to 10, the value of the counter will be incremented until the condition is satisfied. The line echo $counter prints all the numbers from 1 to 10.
While loop in Shell Script
For loop
Like the while loop, a for loop is used to execute code iteratively. I.e. repeat code execution as many times as possible defined by the user.
The for loop below iterates through 1 right through 10 and processes their values on the screen.
For loop in Shell Script
A better way to achieve this is to define a range using the double curly braces < >as shown instead of typing all the numbers.
Bash Positional Parameters
A positional parameter is a special variable that is referenced in the script when values are passed on the shell but cannot be assigned. Positional parameters run from $0 $1 $2 $3 …… to $9. Beyond the $9 value, the parameters have to be enclosed in curly brackets e.g $<10>, $ <11>… and so on.
When executing the script, the first positional parameter which is $0 takes the name of the shell script. The $1 parameter takes the first variable that is passed on the terminal, $2 takes the second, $3 the third and so on.
Let’s create a script test.sh as shown.
Next, execute the script and provide the first and second name as the arguments:
Bash Positional Parameter
From the output, we can see that the first variable that is printed is the name of the shell script, in this case, test.sh. Thereafter, the names are printed out corresponding to the positional parameters defined in the shell script.
Positional parameters are useful in that they help you customize the data being entered instead of explicitly assigning a value to a variable.
Shell Command Exit Codes
Let’s begin by answering a simple question, What is an exit code?
Every command executed on the shell by a user or shell script has an exit status. An exit status is an integer.
An exit status of 0 implies that the command executed successfully without any errors. Anything between 1 to 255 shows that the command failed or did not execute successfully.
To find the exit status of a command, use the $? Shell variable.
An exit status of 1 points to a general error or any impermissible errors such as editing files without sudo permissions.
An exit status of 2 points to incorrect usage of a command or builtin shell variable.
The 127 exit status points to an illegal command which usually yields the ‘command not found’ error.
Find Exit Status of Command
Processing Output of Shell Commands within a Script
In bash scripting, you can store the output of a command in a variable for future use. This is also referred to as shell command substitution and can be achieved in the following ways.
For example, you can store the date command in a variable called today and call the shell script to reveal the current date.
Print Date Using Shell Script
Let’s take another example. Suppose you want to find the valid login users on your Linux system. How would you go about it? First, the list of all the users (both system, process, and login users) is stored in the /etc/passwd file.
To view the file, you’d need to use the cat command. However, to narrow down to log in users, use the grep command to search for users with the /bin/bash attribute and use the cut -c 1-10 command as shown to display the first 10 characters of the names.
We have stored the cat command to the login_users variable.
List Logged in Users
This brings our tutorial on creating simple shell scripts to an end. We hope you found this valuable.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
ИТ База знаний
Курс по 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 означает, что пользователь вводит свой ответ в той же строке, что и приглашение.
Человек, запускающий сценарий, увидит приглашение и введет ответ :
Использование аргументов командной строки
Чтобы использовать аргументы, которые пользователь вводит вместе с именем скрипта, необходимо знать, как их идентифицировать. Аргументам скрипта будут присвоены имена $1 , $2 и так далее. Для любого аргумента, который вы собираетесь использовать неоднократно, вы можете рассмотреть возможность присвоения этих значений более значимым именам переменных.
В этом случае мы проверяем, является ли первый предоставленный аргумент числовым, и закрываем скрипт, если это не так. Если ответ — число, то далее назначаем его переменной $loops , чтобы использовать позже в скрипте.
Еще одна полезная вещь, которую нужно сделать в скрипте, — это сначала проверить наличие аргументов. В противном случае синтаксис, подобный показанному выше, не сработает, потому что оболочка увидит выражение if [[! = 6 *]]; , что приведет к синтаксической ошибке.
Чтобы проверить правильность количества предоставленных аргументов, вы можете использовать синтаксис, подобный приведенному ниже, который проверяет, были ли предоставлены по крайней мере два аргумента, и, в противном случае, напоминает пользователю, что требуется как количество строк, так и имя файла:
Различные способы создания циклов
Есть несколько способов сделать цикл внутри скрипта. Используйте for , если вы хотите повторить действие заданное количество раз. Например:
Используйте while , если хотите выполнять какое-то действие, пока условие существует или не существует.
Использование оператора case
Операторы case позволяют вашим скриптам реагировать по-разному в зависимости от того, какие значения проверяются. В приведенном ниже скрипте используются разные команды для извлечения содержимого файла, предоставленного в качестве аргумента, путем определения типа файла.
Обратите внимание, что этот сценарий также запрашивает имя файла, если оно не было предоставлено, а затем проверяет, действительно ли указанный файл существует. Только после этого выполняется извлечение.
Реакция на ошибки
Вы можете обнаруживать ошибки в скриптах и реагировать на них и тем самым избегать других ошибок. Хитрость заключается в том, чтобы проверять выходные коды после запуска команд. Если код выхода имеет значение, отличное от нуля, произошла ошибка. В этом скрипте проверяется, запущен ли Apache, но отправляем результат проверки в /dev/null . Затем проверяем, не равен ли код выхода нулю, поскольку это означает, что команда ps не получила ответа. Если код выхода не равен нулю, сценарий сообщает пользователю, что Apache не запущен.
Мини — курс по виртуализации
Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
Источник