Bash

Bash

This topic about scripts written for the Bash command shell.

Извлечь базовое имя файла без пути и расширения в Bash

Команда basename обычно используется в Bash для извлечения базового имени файла или каталога по заданному пути путем удаления всех ведущих компонентов каталога. В этой статье мы рассмотрим, как извлечь базовое имя файла без его пути и расширения с помощью bash.

Извлечь базовое имя файла без пути и расширения в Bash

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

#!bin/bash
filepath=/home/aaliyan/bash3.sh
s=$(basename $filepath)
echo "${s%.*}"

Приведенный выше сценарий bash определяет переменную с именем « filepath » и назначает ей путь к файлу « /home/aaliyan/bash3.sh ». Затем сценарий использует команду basename для извлечения базового имени файла из пути к файлу и присваивает результат переменной с именем «s».

Расширение второго параметра удаляет расширение из имени файла, удаляя кратчайшее возможное совпадение любого количества символов, за которым следует точка, используя «%.*». Полученная строка «bash3» затем выводится на консоль с помощью команды echo:

Другой способ извлечь базовое имя файла без его пути к файлу и расширения — использовать расширение параметра без использования команды basename. Ниже приведен пример кода bash, который использует метод расширения параметра для получения базового имени файла без файла. путь и расширение файла:

#!bin/bash
filepath=/home/aaliyan/bash3.sh
s=${filepath##*/}
echo "${s%.*}"

Это сценарий bash, который определяет переменную с именем «filepath» и присваивает ей значение « /home/aaliyan/bash3.sh ». Затем сценарий дважды использует функцию расширения параметра bash для извлечения базового имени файла без его пути и расширения. В частности, раскрытие первого параметра удаляет путь из имени файла, удаляя максимально возможное совпадение любого количества символов, за которым следует косая черта с использованием «##/».

Полученная строка « bash3.sh » затем присваивается переменной с именем «s». Расширение второго параметра удаляет расширение из имени файла, удаляя кратчайшее возможное совпадение любого количества символов, за которым следует точка с использованием «%.». Полученная строка «bash3» затем выводится на консоль с помощью команды echo:

Заключение

Извлечение базового имени файла без его пути и расширения — обычная задача в сценариях bash. Используя команду basename в сочетании с функциями подстановки и расширения параметров bash, мы можем легко решить эту задачу. Это может быть полезно при работе с именами файлов в скриптах, например, при переименовании файлов или выполнении операций над файлами с похожими именами.

Оригинальный источник статьи: https://linuxhint.com/

#bash #file #path #extension 

Извлечь базовое имя файла без пути и расширения в Bash
津田  淳

津田 淳

1679799000

在 Bash 中提取没有路径和扩展名的文件基名

basename 命令常用于 Bash 中,通过删除任何前导目录组件从给定路径中检索文件或目录的基本名称。本文将探讨如何使用 bash 提取不带路径和扩展名的文件的基本名称。

在 Bash 中提取没有路径和扩展名的文件基名

要提取没有路径和扩展名的文件的基本名称,我们可以结合使用 basename 命令和 bash 的参数替换功能。basename 命令返回路径名的最后一个组成部分,在我们的例子中是带有扩展名的文件名。但是,通过指定后缀选项,我们可以从文件名中去掉扩展名,下面是一个示例 bash 代码:

#!bin/bash
filepath=/home/aaliyan/bash3.sh
s=$(basename $filepath)
echo "${s%.*}"

上面的 bash 脚本定义了一个名为“ filepath ”的变量,并将文件“ /home/aaliyan/bash3.sh ”的路径分配给它。然后脚本使用 basename 命令从文件路径中提取文件的基本名称,并将结果分配给名为“s”的变量。

第二个参数扩展通过使用“%.*”删除后跟任意数量字符的最短可能匹配项,从文件名中删除扩展名。然后使用 echo 命令将生成的字符串“bash3”打印到控制台:

另一种提取不带文件路径和扩展名的文件的基本名称的方法是使用不使用 basename 命令的参数扩展,下面是使用参数扩展方法获取不带文件的文件的基本名称的示例 bash 代码路径和文件扩展名:

#!bin/bash
filepath=/home/aaliyan/bash3.sh
s=${filepath##*/}
echo "${s%.*}"

这是一个 bash 脚本,它定义了一个名为“文件路径”的变量,并为其分配了值“ /home/aaliyan/bash3.sh ”。然后,该脚本两次使用 bash 的参数扩展功能来提取文件的基本名称,而无需其路径和扩展名。具体来说,第一个参数扩展通过使用“##/”删除后跟正斜杠的任意数量字符的最长可能匹配,从文件名中删除路径。

然后将生成的字符串“ bash3.sh ”分配给名为“s”的变量。第二个参数扩展通过删除任意数量字符的最短可能匹配后跟使用“%.”的点,从文件名中删除扩展名。然后使用 echo 命令将生成的字符串“bash3”打印到控制台:

结论

提取没有路径和扩展名的文件的基本名称是 bash 脚本中的常见任务。通过使用basename 命令结合bash 的参数替换和参数扩展特性,我们可以很容易地完成这个任务。这在处理脚本中的文件名时非常有用,例如,重命名文件或对具有相似名称的文件执行操作时。

文章原文出处:https: //linuxhint.com/

#bash #file #path #extension 

在 Bash 中提取没有路径和扩展名的文件基名

Блочные комментарии в оболочке Script-Bash

В сценариях оболочки комментарии используются для аннотирования кода, что облегчает разработчикам понимание цели, функциональности и реализации сценария. В некоторых случаях мы можем захотеть временно отключить или «заблокировать» определенные разделы кода для целей отладки или тестирования, не удаляя их полностью. Этого можно добиться, используя блочные комментарии в сценариях оболочки, и в этой статье обсуждается, как блокировать комментарии в сценариях оболочки.

Блокировать комментарии в сценарии оболочки

Блочные комментарии — это комментарии, которые могут занимать несколько строк кода. В сценариях оболочки мы можем создавать блочные комментарии, заключая комментарии в маркеры <<'EOF' и 'EOF' . Синтаксис блочных комментариев следующий:

: '
code line1
code line2
code line3
'

В приведенном выше синтаксисе символ: используется для обозначения пустой команды, которая позволяет выполнить комментарий к блоку без возникновения ошибки. Текст комментария заключен в одинарные кавычки ' и может занимать несколько строк. Маркеры EOF в начале и конце комментария указывают на начало и конец комментария блока. Вот пример того, как использовать блочные комментарии в сценарии оболочки:

#!/bin/bash
echo "Starting the script..."
: '
This section of the code is commented out for testing purposes.
echo "instruction not to be executed."
echo "instruction not to be executed."
echo "instruction not to be executed."
'
echo "Continuing with the script..."
echo "The script has finished."

Здесь мы использовали блочные комментарии, чтобы временно отключить часть кода в целях тестирования. Комментарий к блоку начинается с символа:, за которым следует маркер <<'EOF' . Текст комментария заключен в одинарные кавычки и занимает три строки. Комментарий блока заканчивается маркером 'EOF' .

Заключение

Блочные комментарии — это полезная функция в сценариях оболочки для временного отключения или комментирования разделов кода. Используя блочные комментарии, мы можем легко отлаживать и тестировать наши сценарии оболочки без постоянного удаления или изменения кода. Синтаксис блочных комментариев в сценариях оболочки прост и удобен в использовании. Включая блочные комментарии в наши сценарии оболочки, мы можем писать более чистый и эффективный код.

Оригинальный источник статьи: https://linuxhint.com/

#bash #shell #comments 

Блочные комментарии в оболочке Script-Bash
津田  淳

津田 淳

1679794620

在 Shell Script-Bash 中阻止注释

在 shell 脚本中,注释用于注释代码,使开发人员更容易理解脚本的目的、功能和实现。在某些情况下,我们可能希望暂时禁用或“阻止”代码的某些部分以进行调试或测试,而不是完全删除它们。这可以在 shell 脚本中使用块注释来实现,本文将讨论如何在 shell 脚本中块注释。

在 Shell 脚本中阻止注释

块注释是可以跨越多行代码的注释。在 shell 脚本中,我们可以通过将注释包含在<<'EOF''EOF'标记中来创建块注释。块注释的语法如下:

: '
code line1
code line2
code line3
'

在上面的语法中,: 字符用于表示一个空命令,该命令允许执行块注释而不产生错误。注释文本用单引号 ' 括起来,可以跨越多行。注释开头和结尾的 EOF 标记表示块注释的开始和结束。以下是如何在 shell 脚本中使用块注释的示例:

#!/bin/bash
echo "Starting the script..."
: '
This section of the code is commented out for testing purposes.
echo "instruction not to be executed."
echo "instruction not to be executed."
echo "instruction not to be executed."
'
echo "Continuing with the script..."
echo "The script has finished."

在这里,我们使用块注释暂时禁用一段代码以用于测试目的。块注释以: 字符开头,后跟<<'EOF'标记。注释文本包含在单引号内并跨越三行。块注释以“EOF”标记结束。

结论

块注释是 shell 脚本中的一个有用功能,用于暂时禁用或注释掉代码部分。通过使用块注释,我们可以轻松地调试和测试我们的 shell 脚本,而无需永久删除或修改代码。shell 脚本中块注释的语法简单易用。通过将块注释合并到我们的 shell 脚本中,我们可以编写更清晰、更高效的代码。

文章原文出处:https: //linuxhint.com/

#bash #shell #comments 

在 Shell Script-Bash 中阻止注释

Extract File Basename Without Path and Extension in Bash

The basename command is commonly used in Bash to retrieve the base name of a file or directory from a given path by removing any leading directory components. This article will explore how to extract the base name of a file without its path and extension using bash.

Extract File Basename Without Path and Extension in Bash

To extract the basename of a file without its path and extension, we can use the basename command in conjunction with the parameter substitution feature of bash. The basename command returns the last component of a pathname, which in our case would be the file name with its extension. However, by specifying the suffix option, we can strip the extension from the file name, here’s an example bash code:

#!bin/bash
filepath=/home/aaliyan/bash3.sh
s=$(basename $filepath)
echo "${s%.*}"

The above bash script defines a variable called “filepath” and assigns it the path of the file “/home/aaliyan/bash3.sh“. The script then uses the basename command to extract the base name of the file from the file path and assigns the result to a variable called “s”.

The second parameter expansion removes the extension from the file name by removing the shortest possible match of any number of characters followed by a dot using “%.*”. The resulting string, “bash3”, is then printed to the console using the echo command:

Another way to extract the basename of a file without its file path and extension is by using the parameter expansion that is without using the basename command, below is the example bash code that uses the parameter expansion method to get the basename of a file without file path and file extension:

#!bin/bash
filepath=/home/aaliyan/bash3.sh
s=${filepath##*/}
echo "${s%.*}"

This is a bash script that defines a variable called “filepath” and assigns it the value “/home/aaliyan/bash3.sh“. The script then uses the parameter expansion feature of bash twice to extract the basename of the file without its path and extension. Specifically, the first parameter expansion removes the path from the file name by removing the longest possible match of any number of characters followed by a forward slash using “##/”.

The resulting string, “bash3.sh” is then assigned to a variable called “s”. The second parameter expansion removes the extension from the file name by removing the shortest possible match of any number of characters followed by a dot using “%.”. The resulting string, “bash3”, is then printed to the console using the echo command:

Conclusion

Extracting the basename of a file without its path and extension is a common task in bash scripting. By using the basename command in combination with the parameter substitution and parameter expansion features of bash, we can easily achieve this task. This can be useful when working with file names in scripts, for example, when renaming files or performing operations on files with similar names.

Original article source at: https://linuxhint.com/

#bash #file #path #extension 

Extract File Basename Without Path and Extension in Bash

Block Comments in a Shell Script-Bash

In shell scripting, comments are used to annotate the code, making it easier for developers to understand the script’s purpose, functionality, and implementation. In some cases, we may want to temporarily disable or “block” certain sections of the code for debugging or testing purposes without deleting them altogether. This can be achieved using block comments in shell scripting and this article will discuss how to block comments in a shell script.

Block Comments in a Shell Script

Block comments are comments that can span multiple lines of code. In shell scripting, we can create block comments by enclosing the comments within the <<'EOF' and ‘EOF’ markers. The syntax of block comments is as follows:

: '
code line1
code line2
code line3
'

In the above syntax, the: character is used to denote an empty command that allows the block comment to be executed without generating an error. The comment text is enclosed within single quotes ‘ and can span multiple lines. The EOF markers at the beginning and end of the comment indicate the start and end of the block comment. Here’s an example of how to use block comments in a shell script:

#!/bin/bash
echo "Starting the script..."
: '
This section of the code is commented out for testing purposes.
echo "instruction not to be executed."
echo "instruction not to be executed."
echo "instruction not to be executed."
'
echo "Continuing with the script..."
echo "The script has finished."

Here, we have used block comments to temporarily disable a section of the code for testing purposes. The block comment starts with the: character, followed by the <<'EOF' marker. The comment text is enclosed within single quotes and spans three lines. The block comment ends with the ‘EOF’ marker.

Conclusion

Block comments are a useful feature in shell scripting for temporarily disabling or commenting out sections of code. By using block comments, we can easily debug and test our shell scripts without deleting or modifying the code permanently. The syntax of block comments in shell scripting is simple and easy to use. By incorporating block comments into our shell scripts, we can write cleaner and more efficient code.

Original article source at: https://linuxhint.com/

#bash #shell #comments 

Block Comments in a Shell Script-Bash

Shell_GPT: A Command-line Productivity tool Powered By ChatGPT

Shell GPT

A command-line productivity tool powered by OpenAI's ChatGPT (GPT-3.5). As developers, we can leverage ChatGPT capabilities to generate shell commands, code snippets, comments, and documentation, among other things. Forget about cheat sheets and notes, with this tool you can get accurate answers right in your terminal, and you'll probably find yourself reducing your daily Google searches, saving you valuable time and effort.

Installation

pip install shell-gpt

You'll need an OpenAI API key, you can generate one here.

If the$OPENAI_API_KEY environment variable is set it will be used, otherwise, you will be prompted for your key which will then be stored in ~/.config/shell_gpt/.sgptrc.

Usage

sgpt has a variety of use cases, including simple queries, shell queries, and code queries.

Simple queries

We can use it as normal search engine, asking about anything:

sgpt "nginx default config file location"
# -> The default configuration file for Nginx is located at /etc/nginx/nginx.conf.
sgpt "docker show all local images"
# -> You can view all locally available Docker images by running: `docker images`
sgpt "mass of sun"
# -> = 1.99 × 10^30 kg

Conversion

Convert various units and measurements without having to search for the conversion formula or use a separate conversion website. You can convert units such as time, distance, weight, temperature, and more.

sgpt "1 hour and 30 minutes to seconds"
# -> 5,400 seconds
sgpt "1 kilometer to miles"
# -> 1 kilometer is equal to 0.62137 miles.

Shell commands

Have you ever found yourself forgetting common shell commands, such as chmod, and needing to look up the syntax online? With --shell option, you can quickly find and execute the commands you need right in the terminal.

sgpt --shell "make all files in current directory read only"
# -> chmod 444 *

Since we are receiving valid shell command, we can execute it using eval $(sgpt --shell "make all files in current directory read only") but this is not very convenient, instead we can use --execute (or shortcut -se for --shell --execute) parameter:

sgpt --shell --execute "make all files in current directory read only"
# -> chmod 444 *
# -> Execute shell command? [y/N]: y
# ...

Shell GPT is aware of OS and $SHELL you are using, it will provide shell command for specific system you have. For instance, if you ask sgpt to update your system, it will return a command based on your OS. Here's an example using macOS:

sgpt -se "update my system"
# -> sudo softwareupdate -i -a

The same prompt, when used on Ubuntu, will generate a different suggestion:

sgpt -se "update my system"
# -> sudo apt update && sudo apt upgrade -y

Let's try some docker containers:

sgpt -se "start nginx using docker, forward 443 and 80 port, mount current folder with index.html"
# -> docker run -d -p 443:443 -p 80:80 -v $(pwd):/usr/share/nginx/html nginx
# -> Execute shell command? [y/N]: y
# ...

Also, we can provide some parameters name in our prompt, for example, passing output file name to ffmpeg:

sgpt -se "slow down video twice using ffmpeg, input video name \"input.mp4\" output video name \"output.mp4\""
# -> ffmpeg -i input.mp4 -filter:v "setpts=2.0*PTS" output.mp4
# -> Execute shell command? [y/N]: y
# ...

We can apply additional shell magic in our prompt, in this example passing file names to ffmpeg:

ls
# -> 1.mp4 2.mp4 3.mp4
sgpt -se "using ffmpeg combine multiple videos into one without audio. Video file names: $(ls -m)"
# -> ffmpeg -i 1.mp4 -i 2.mp4 -i 3.mp4 -filter_complex "[0:v] [1:v] [2:v] concat=n=3:v=1 [v]" -map "[v]" out.mp4
# -> Execute shell command? [y/N]: y
# ...

Since ChatGPT can also do summarization and analyzing of input text, we can ask it to generate commit message:

sgpt "Generate git commit message, my changes: $(git diff)"
# -> Commit message: Implement Model enum and get_edited_prompt() func, add temperature, top_p and editor args for OpenAI request.

Or ask it to find error in logs and provide more details:

sgpt "check these logs, find errors, and explain what the error is about: ${docker logs -n 20 container_name}"
# ...

Generating code

With --code parameters we can query only code as output, for example:

sgpt --code "Solve classic fizz buzz problem using Python"
for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Since it is valid python code, we can redirect the output to file:

sgpt --code "solve classic fizz buzz problem using Python" > fizz_buzz.py
python fizz_buzz.py
# 1
# 2
# Fizz
# 4
# Buzz
# Fizz
# ...

Chat

To start a chat session, use the --chat option followed by a unique session name and a prompt:

sgpt --chat number "please remember my favorite number: 4"
# -> I will remember that your favorite number is 4.
sgpt --chat number "what would be my favorite number + 4?"
# -> Your favorite number is 4, so if we add 4 to it, the result would be 8.

You can also use chat sessions to iteratively improve ChatGPT's suggestions by providing additional clues.

sgpt --chat python_requst --code "make an example request to localhost using Python"
import requests

response = requests.get('http://localhost')
print(response.text)

Asking ChatGPT to add a cache to our request.

sgpt --chat python_request --code "add caching"
import requests
from cachecontrol import CacheControl

sess = requests.session()
cached_sess = CacheControl(sess)

response = cached_sess.get('http://localhost')
print(response.text)

We can use --code or --shell options to initiate --chat, so you can keep refining the results:

sgpt --chat sh --shell "What are the files in this directory?"
# -> ls
sgpt --chat sh "Sort them by name"
# -> ls | sort
sgpt --chat sh "Concatenate them using FFMPEG"
# -> ffmpeg -i "concat:$(ls | sort | tr '\n' '|')" -codec copy output.mp4
sgpt --chat sh "Convert the resulting file into an MP3"
# -> ffmpeg -i output.mp4 -vn -acodec libmp3lame -ac 2 -ab 160k -ar 48000 final_output.mp3

Chat sessions

To list all the current chat sessions, use the --list-chat option:

sgpt --list-chat
# .../shell_gpt/chat_cache/number
# .../shell_gpt/chat_cache/python_request

To show all the messages related to a specific chat session, use the --show-chat option followed by the session name:

sgpt --show-chat number
# user: please remember my favorite number: 4
# assistant: I will remember that your favorite number is 4.
# user: what would be my favorite number + 4?
# assistant: Your favorite number is 4, so if we add 4 to it, the result would be 8.

Request cache

Control cache using --cache (default) and --no-cache options. This caching applies for all sgpt requests to OpenAI API:

sgpt "what are the colors of a rainbow"
# -> The colors of a rainbow are red, orange, yellow, green, blue, indigo, and violet.

Next time, same exact query will get results from local cache instantly. Note that sgpt "what are the colors of a rainbow" --temperature 0.5 will make a new request, since we didn't provide --temperature (same applies to --top-probability) on previous request.

This is just some examples of what we can do using ChatGPT model, I'm sure you will find it useful for your specific use cases.

Runtime configuration file

You can setup some parameters in runtime configuration file ~/.config/shell_gpt/.sgptrc:

# API key, also it is possible to define OPENAI_API_KEY env.
OPENAI_API_KEY=your_api_key
# OpenAI host, useful if you would like to use proxy.
OPENAI_API_HOST=https://api.openai.com
# Max amount of cached message per chat session.
CHAT_CACHE_LENGTH=100
# Chat cache folder.
CHAT_CACHE_PATH=/tmp/shell_gpt/chat_cache
# Request cache length (amount).
CACHE_LENGTH=100
# Request cache folder.
CACHE_PATH=/tmp/shell_gpt/cache
# Request timeout in seconds.
REQUEST_TIMEOUT=60

Full list of arguments

╭─ Arguments ───────────────────────────────────────────────────────────────────────────────────────────────╮
│   prompt      [PROMPT]  The prompt to generate completions for.                                           │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --temperature      FLOAT RANGE [0.0<=x<=1.0]  Randomness of generated output. [default: 1.0]              │
│ --top-probability  FLOAT RANGE [0.1<=x<=1.0]  Limits highest probable tokens (words). [default: 1.0]      │
│ --chat             TEXT                       Follow conversation with id (chat mode). [default: None]    │
│ --show-chat        TEXT                       Show all messages from provided chat id. [default: None]    │
│ --list-chat                                   List all existing chat ids. [default: no-list-chat]         │
│ --shell                                       Provide shell command as output.                            │
│ --execute                                     Will execute --shell command.                               │
│ --code                                        Provide code as output. [default: no-code]                  │
│ --editor                                      Open $EDITOR to provide a prompt. [default: no-editor]      │
│ --cache                                       Cache completion results. [default: cache]                  │
│ --animation                                   Typewriter animation. [default: animation]                  │
│ --spinner                                     Show loading spinner during API request. [default: spinner] │
│ --help                                        Show this message and exit.                                 │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────╯

Docker

Run the container using the OPENAI_API_KEY environment variable, and a docker volume to store cache:

docker run --rm \
           --env OPENAI_API_KEY="your OPENAI API key" \
           --volume gpt-cache:/tmp/shell_gpt \
       ghcr.io/ther1d/shell_gpt --chat rainbow "what are the colors of a rainbow"

Example of a conversation, using an alias and the OPENAI_API_KEY environment variable:

alias sgpt="docker run --rm --env OPENAI_API_KEY --volume gpt-cache:/tmp/shell_gpt ghcr.io/ther1d/shell_gpt"
export OPENAI_API_KEY="your OPENAI API key"
sgpt --chat rainbow "what are the colors of a rainbow"
sgpt --chat rainbow "inverse the list of your last answer"
sgpt --chat rainbow "translate your last answer in french"

You also can use the provided Dockerfile to build your own image:

docker build -t sgpt .

Download Details:

Author: TheR1D
Source Code: https://github.com/TheR1D/shell_gpt 
License: MIT license

#chatgpt #openai #gpt #python #linux #shell #bash #cli 

Shell_GPT: A Command-line Productivity tool Powered By ChatGPT

Команда Expect, автоматизировать сценарии оболочки, как по волшебству

В предыдущем посте мы говорили о написании практических сценариев оболочки и увидели, как легко написать сценарий оболочки. Сегодня мы поговорим об инструменте, который творит чудеса с нашими сценариями оболочки; этим инструментом является команда Expect или язык сценариев Expect .

Команда Expect или язык ожидающих сценариев — это язык, который взаимодействует с вашими интерактивными программами или сценариями, требующими взаимодействия с пользователем.

Язык сценариев Expect работает, ожидая ввода, затем сценарий Expect отправит ответ без какого-либо взаимодействия с пользователем.

Можно сказать, что этот инструмент — ваш робот, который будет автоматизировать ваши скрипты.

Если команда expect не установлена ​​в вашей системе, вы можете установить ее с помощью следующей команды:

$ apt-get install expect

Или в системах на базе Red Hat, таких как CentOS:

$ yum install expect

Ожидать команды

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

порождатьЗапускает скрипт или программу.
ожидатьОжидает вывода программы.
отправлятьОтправляет ответ вашей программе.
взаимодействоватьПозволяет взаимодействовать с вашей программой.
  • Команда spawn запускает сценарий или программу, такую ​​как оболочка, FTP , Telnet, SSH, SCP и т. д.
  • Команда send отправляет ответ сценарию или программе.
  • Команда Expect ожидает ввода.
  • Команда взаимодействия позволяет определить предопределенное взаимодействие с пользователем.

Мы собираемся ввести сценарий оболочки, который задает некоторые вопросы, и мы создадим сценарий Expect, который ответит на эти вопросы.

Во-первых, сценарий оболочки будет выглядеть так:

#!/bin/bash

echo "Hello, who are you?"

read $REPLY

echo "Can I ask you some questions?"

read $REPLY

echo "What is your favorite topic?"

read $REPLY

Теперь напишем Expect-скрипты, которые ответят на это автоматически:

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Im Adam\r"

expect "Can I ask you some questions?\r"

send -- "Sure\r"

expect "What is your favorite topic?\r"

send -- "Technology\r"

expect eof

Первая строка определяет ожидаемый путь команды, который

#!/usr/bin/expect

Во второй строке кода отключаем тайм-аут. Затем запустите наш скрипт с помощью команды spawn.

Мы можем использовать spawn для запуска любой программы или любого другого интерактивного скрипта.

Остальные строки — это сценарий Expect, который взаимодействует с нашим сценарием оболочки.

Последняя строка означает конец взаимодействия.

Теперь Showtime, давайте запустим нашего бота ответов и убедитесь, что вы сделали его исполняемым.

$ chmod +x ./answerbot
$./answerbot

Прохладный!! Команда отправки ответила на все вопросы.

Если вы получаете ошибки относительно местоположения команды Expect, вы можете получить местоположение с помощью команды which:

$ which expect

Мы вообще не взаимодействовали с нашим скриптом; программа Expect делает всю работу за нас.

Вы можете применить описанный выше метод к любому интерактивному сценарию или программе. Хотя приведенный выше сценарий Expect очень прост в написании, возможно, сценарий Expect немного сложен для некоторых людей, но он у вас есть.

Использование автоожидания

Для автоматического создания сценария ожидания вы можете использовать команду autoexpect.

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

$ autoexpect ./questions

Автоожидание генерирует файл с именем script.exp, содержащий тот же код, что и выше, с некоторыми дополнениями, которые мы пока оставим.

Если вы запустите автоматически сгенерированный файл script.exp, вы увидите те же ответы, что и ожидались:

Потрясающий!! Это супер легко.

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

Работа с переменными

Вы можете использовать команду set для определения переменных в ожидаемых сценариях следующим образом:

set MYVAR 5

Чтобы получить доступ к переменной, поставьте перед ней $, например $VAR1.

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

set MYVAR [lindex $argv 0]

Здесь мы определяем переменную MYVAR, которая равна первому переданному аргументу.

Вы можете получить первый и второй аргументы и сохранить их в таких переменных:

set my_name [lindex $argv 0]

set my_favorite [lindex $argv 1]

Добавим в наш скрипт переменные:

#!/usr/bin/expect -f

set my_name [lindex $argv 0]

set my_favorite [lindex $argv 1]

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Im $my_name\r"

expect "Can I ask you some questions?\r"

send -- "Sure\r"

expect "What is your favorite topic?\r"

send -- "$my_favorite\r"

expect eof

Теперь попробуйте запустить скрипт Expect с некоторыми параметрами, чтобы увидеть результат:

$ ./answerbot SomeName Programming

Потрясающий!! Теперь наш автоматизированный скрипт Expect стал более динамичным.

Условные тесты

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

expect {

    "something" { send -- "send this\r" }

    "*another" { send -- "send another\r" }

}

Мы собираемся изменить наш сценарий, чтобы он возвращал различные условия, и мы изменим наш сценарий Expect, чтобы он обрабатывал эти условия.

Мы собираемся эмулировать различные ожидания с помощью следующего скрипта:

#!/bin/bash

let number=$RANDOM

if [ $number -gt 25000 ]; then

	echo "What is your favorite topic?"

else

	echo "What is your favorite movie?"

fi

read $REPLY

Когда вы запускаете скрипт, он каждый раз генерирует случайное число и на основе этого числа; мы ставим условие возврата разных ожиданий.

Давайте напишем ожидающий скрипт, который с этим справится.

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect {

    "*topic?" { send -- "Programming\r" }

    "*movie?" { send -- "Star wars\r" }

}

expect eof

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

Если еще Условия

Вы можете использовать предложения if/else в ожидаемых сценариях следующим образом:

#!/usr/bin/expect -f

set NUM 1

if { $NUM < 5 } {

    puts "\Smaller than 5\n"

} elseif { $NUM > 5 } {

    puts "\Bigger than 5\n"

} else {

    puts "\Equals 5\n"

}

Примечание. Открывающая фигурная скобка должна находиться на той же строке .

Пока циклы

В то время как циклы в языке ожидания должны использовать фигурные скобки, чтобы содержать выражение, подобное этому:

#!/usr/bin/expect -f

set NUM 0

while { $NUM <= 5 } {

    puts "\nNumber is $NUM"

    set NUM [ expr $NUM + 1 ]

}

puts ""

Для циклов

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

#!/usr/bin/expect -f

for {set NUM 0} {$NUM <= 5} {incr NUM} {

    puts "\nNUM = $NUM"

}

puts ""

Пользовательские функции

Вы можете определить функцию, используя proc следующим образом:

proc myfunc { TOTAL } {

    set TOTAL [expr $TOTAL + 1]

    return "$TOTAL"

}

И вы можете использовать их после этого.

#!/usr/bin/expect -f

proc myfunc { TOTAL } {

    set TOTAL [expr $TOTAL + 1]

    return "$TOTAL"

}

set NUM 0

while {$NUM <= 5} {

    puts "\nNumber $NUM"

    set NUM [myfunc $NUM]

}

puts ""

Команда взаимодействия

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

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

Когда вы используете команду взаимодействия, expect начнет чтение с клавиатуры.

Этот сценарий оболочки спросит пароль, как показано ниже:

#!/bin/bash

echo "Hello, who are you?"

read $REPLY

echo "What is you password?"

read $REPLY

echo "What is your favorite topic?"

read $REPLY

Теперь напишем ожидающий скрипт, который будет запрашивать пароль:

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Hi Im Adam\r"

expect "*password?\r"

interact ++ return

send "\r"

expect "*topic?\r"

send -- "Technology\r"

expect eof

После ввода пароля наберите ++ и управление вернется с клавиатуры на скрипт.

Язык Expect портирован на многие языки, такие как C#, Java, Perl, Python, Ruby и Shell, с почти такими же концепциями и синтаксисом из-за его простоты и важности.

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

Я надеюсь, что теперь вы усвоили некоторые из наиболее важных аспектов команды expect, команды autoexpect и того, как использовать ее для более разумной автоматизации ваших задач.

Спасибо.

Оригинальный источник статьи: https://likegeeks.com/

#linux #shell #bash #scripts #command #magic 

Команда Expect, автоматизировать сценарии оболочки, как по волшебству
佐藤  桃子

佐藤 桃子

1679560860

如何使用 Expect 命令像魔术一样自动化 Shell 脚本

在上一篇文章中,我们谈到了编写实用的 shell 脚本,我们看到了编写 shell 脚本是多么容易。今天我们要讨论一个对我们的 shell 脚本有魔力的工具;该工具是Expect 命令Expect 脚本语言

Expect 命令或 Expect 脚本语言是一种与需要用户交互的交互式程序或脚本对话的语言。

Expect 脚本语言通过期待输入来工作,然后 Expect 脚本将发送响应而无需任何用户交互。

您可以说这个工具是您的机器人,它将自动执行您的脚本。

如果您的系统上没有安装 expect 命令,您可以使用以下命令安装它:

$ apt-get install expect

或者在 CentOS 等基于 Red Hat 的系统上:

$ yum install expect

期待命令

在我们谈论 expect 命令之前,让我们看看一些用于交互的 Expect 命令:

产卵启动脚本或程序。
预计等待程序输出。
发送向您的程序发送回复。
相互影响允许您与您的程序进行交互。
  • spawn 命令启动脚本或程序,如 shell、FTP、Telnet、SSH、SCP 等。
  • send 命令发送对脚本或程序的回复。
  • Expect 命令等待输入。
  • interact 命令允许您定义预定义的用户交互。

我们将输入一个 shell 脚本来询问一些问题,然后我们将制作一个 Expect 脚本来回答这些问题。

首先,shell 脚本如下所示:

#!/bin/bash

echo "Hello, who are you?"

read $REPLY

echo "Can I ask you some questions?"

read $REPLY

echo "What is your favorite topic?"

read $REPLY

现在我们将编写将自动回答此问题的 Expect 脚本:

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Im Adam\r"

expect "Can I ask you some questions?\r"

send -- "Sure\r"

expect "What is your favorite topic?\r"

send -- "Technology\r"

expect eof

第一行定义了 expect 命令路径,它是

#!/usr/bin/expect

在第二行代码中,我们禁用超时。然后使用 spawn 命令启动我们的脚本。

我们可以使用 spawn 来运行我们想要的任何程序或任何其他交互式脚本。

其余行是与我们的 shell 脚本交互的 Expect 脚本。

最后一行表示交互结束。

现在 Showtime,让我们运行我们的回答机器人并确保你让它可执行。

$ chmod +x ./answerbot
$./answerbot

凉爽的!!发送命令回答了所有问题。

如果您收到有关 Expect 命令位置的错误,您可以使用 which 命令获取位置:

$ which expect

我们根本没有与我们的脚本进行交互;Expect 程序为我们完成了这项工作。

您可以将上述方法应用于任何交互式脚本或程序。虽然上面的 Expect 脚本很容易写,也许 Expect 脚本对某些人来说有点棘手,但你有它。

使用自动预期

要自动构建 expect 脚本,您可以使用 autoexpect 命令。

autoexpect 的工作方式类似于 expect 命令,但它会为您构建自动化脚本。您将要自动化的脚本作为参数传递给 autoexpect,然后您回答问题,autoexpect 将您的答案保存在一个文件中。

$ autoexpect ./questions

autoexpect 生成一个名为 script.exp 的文件,其中包含与我们上面所做的相同的代码,并添加了一些我们暂时保留的代码。

如果您运行自动生成的文件 script.exp,您将看到与预期相同的答案:

惊人的!!那超级容易。

许多命令会产生多变的输出,例如 FTP 程序,expect 脚本可能会失败或卡住。为了解决这个问题,您可以对可变数据使用通配符,使您的脚本更加灵活。

使用变量

您可以使用 set 命令在 expect 脚本中定义变量,如下所示:

set MYVAR 5

要访问变量,在它前面加上 $ 就像这样 $VAR1

要在 expect 脚本中定义命令行参数,我们使用以下语法:

set MYVAR [lindex $argv 0]

这里我们定义了一个变量 MYVAR,它等于第一个传递的参数。

您可以获得第一个和第二个参数并将它们存储在这样的变量中:

set my_name [lindex $argv 0]

set my_favorite [lindex $argv 1]

让我们在脚本中添加变量:

#!/usr/bin/expect -f

set my_name [lindex $argv 0]

set my_favorite [lindex $argv 1]

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Im $my_name\r"

expect "Can I ask you some questions?\r"

send -- "Sure\r"

expect "What is your favorite topic?\r"

send -- "$my_favorite\r"

expect eof

现在尝试使用一些参数运行 Expect 脚本以查看输出:

$ ./answerbot SomeName Programming

惊人的!!现在我们的自动化 Expect 脚本更加动态。

条件测试

您可以像这样使用大括号编写条件测试:

expect {

    "something" { send -- "send this\r" }

    "*another" { send -- "send another\r" }

}

我们将更改我们的脚本以返回不同的条件,我们将更改我们的 Expect 脚本来处理这些条件。

我们将使用以下脚本模拟不同的期望:

#!/bin/bash

let number=$RANDOM

if [ $number -gt 25000 ]; then

	echo "What is your favorite topic?"

else

	echo "What is your favorite movie?"

fi

read $REPLY

当您运行脚本时,它每次都会生成一个随机数,并基于该数字;我们设置了返回不同期望的条件。

让我们创建处理该问题的 Expect 脚本。

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect {

    "*topic?" { send -- "Programming\r" }

    "*movie?" { send -- "Star wars\r" }

}

expect eof

非常清楚。如果脚本命中主题输出,则expect脚本将发送编程,如果脚本命中电影输出,则expect脚本将发送星球大战。是不是很酷?

If else 条件

您可以在 expect 脚本中使用 if/else 子句,如下所示:

#!/usr/bin/expect -f

set NUM 1

if { $NUM < 5 } {

    puts "\Smaller than 5\n"

} elseif { $NUM > 5 } {

    puts "\Bigger than 5\n"

} else {

    puts "\Equals 5\n"

}

注意:左大括号必须在同一行

循环

expect 语言中的 while 循环必须使用大括号来包含如下表达式:

#!/usr/bin/expect -f

set NUM 0

while { $NUM <= 5 } {

    puts "\nNumber is $NUM"

    set NUM [ expr $NUM + 1 ]

}

puts ""

For 循环

与任何脚本或编程语言一样,您可以使用 for 循环来完成重复性任务,必须指定三个字段,例如以下格式:

#!/usr/bin/expect -f

for {set NUM 0} {$NUM <= 5} {incr NUM} {

    puts "\nNUM = $NUM"

}

puts ""

用户自定义函数

您可以像这样使用 proc 定义一个函数:

proc myfunc { TOTAL } {

    set TOTAL [expr $TOTAL + 1]

    return "$TOTAL"

}

然后你就可以使用它们了。

#!/usr/bin/expect -f

proc myfunc { TOTAL } {

    set TOTAL [expr $TOTAL + 1]

    return "$TOTAL"

}

set NUM 0

while {$NUM <= 5} {

    puts "\nNumber $NUM"

    set NUM [myfunc $NUM]

}

puts ""

互动命令

有时您的 expect 脚本包含一些您不想与使用您的 expect 脚本的其他用户共享的敏感信息,例如密码或任何其他数据。因此,您希望您的脚本从您那里获取此密码并正常继续自动化。

interact 命令将控制权恢复到键盘。

当您使用 interact 命令时,expect 将开始从键盘读取。

此 shell 脚本将询问密码,如下所示:

#!/bin/bash

echo "Hello, who are you?"

read $REPLY

echo "What is you password?"

read $REPLY

echo "What is your favorite topic?"

read $REPLY

现在我们将编写将提示输入密码的 Expect 脚本:

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Hi Im Adam\r"

expect "*password?\r"

interact ++ return

send "\r"

expect "*topic?\r"

send -- "Technology\r"

expect eof

键入密码后,键入 ++,控件将从键盘返回到脚本。

由于其简单性和重要性,Expect 语言被移植到 C#、Java、Perl、Python、Ruby 和 Shell 等概念和语法几乎相同的许多语言。

您可以在质量保证、回声响应时间等网络测量、自动文件传输、更新和许多其他用途中使用 expect 脚本语言。

我希望您现在已经掌握了 expect 命令、autoexpect 命令的一些最重要的方面,以及如何使用它以更智能的方式自动化您的任务。

谢谢。

文章原文出处:https: //likegeeks.com/

#linux #shell #bash #scripts #command #magic 

如何使用 Expect 命令像魔术一样自动化 Shell 脚本
Monty  Boehm

Monty Boehm

1679557037

How to Automate Shell Scripts Like Magic using Expect Command

In the previous post, we talked about writing practical shell scripts, and we saw how it is easy to write a shell script. Today we are going to talk about a tool that does magic to our shell scripts; that tool is the Expect command or Expect scripting language.

Expect command or expect scripting language is a language that talks with your interactive programs or scripts that require user interaction.

Expect scripting language works by expecting input, then the Expect script will send the response without any user interaction.

You can say that this tool is your robot, which will automate your scripts.

If the expect command if not installed on your system, you can install it using the following command:

$ apt-get install expect

Or on Red Hat based systems like CentOS:

$ yum install expect

Expect Command

Before we talk about expect command, Let’s see some of the Expect command which used for interaction:

spawnStarts a script or a program.
expectWaits for program output.
sendSends a reply to your program.
interactAllows you to interact with your program.
  • The spawn command starts a script or a program like the shell, FTP, Telnet, SSH, SCP, and so on.
  • The send command sends a reply to a script or a program.
  • The Expect command waits for input.
  • The interact command allows you to define a predefined user interaction.

We are going to type a shell script that asks some questions, and we will make an Expect script that will answer those questions.

First, the shell script will look like this:

#!/bin/bash

echo "Hello, who are you?"

read $REPLY

echo "Can I ask you some questions?"

read $REPLY

echo "What is your favorite topic?"

read $REPLY

Now we will write the Expect scripts that will answer this automatically:

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Im Adam\r"

expect "Can I ask you some questions?\r"

send -- "Sure\r"

expect "What is your favorite topic?\r"

send -- "Technology\r"

expect eof

The first line defines the expect command path which is

#!/usr/bin/expect

On the second line of code, we disable the timeout. Then start our script using spawn command.

We can use spawn to run any program we want or any other interactive script.

The remaining lines are the Expect script that interacts with our shell script.

The last line means the end of the interaction.

Now Showtime, let’s run our answer bot and make sure you make it executable.

$ chmod +x ./answerbot
$./answerbot

Cool!! The send command answered all questions.

If you get errors about the location of Expect command you can get the location using the which command:

$ which expect

We did not interact with our script at all; the Expect program does the job for us.

You can apply the above method to any interactive script or program. Although the above Expect script is very easy to write, maybe the Expect script little tricky for some people, well you have it.

Using autoexpect

To build an expect script automatically, you can use the autoexpect command.

autoexpect works like expect command, but it builds the automation script for you. You pass the script you want to automate to autoexpect as a parameter, and you answer the questions, and autoexpect saves your answers in a file.

$ autoexpect ./questions

The autoexpect generates a file called script.exp contains the same code as we did above with some additions that we will leave it for now.

If you run the auto-generated file script.exp, you will see the same answers as expected:

Awesome!! That super easy.

Many commands produce changeable output, like the case of FTP programs, the expect script may fail or stuck. To solve this problem, you can use wildcards for the changeable data to make your script more flexible.

Working with Variables

You can use the set command to define variables in expect scripts like this:

set MYVAR 5

To access the variable, precede it with $ like this $VAR1

To define command line arguments in expect scripts, we use the following syntax:

set MYVAR [lindex $argv 0]

Here we define a variable MYVAR, which equals the first passed argument.

You can get the first and the second arguments and store them in variables like this:

set my_name [lindex $argv 0]

set my_favorite [lindex $argv 1]

Let’s add variables to our script:

#!/usr/bin/expect -f

set my_name [lindex $argv 0]

set my_favorite [lindex $argv 1]

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Im $my_name\r"

expect "Can I ask you some questions?\r"

send -- "Sure\r"

expect "What is your favorite topic?\r"

send -- "$my_favorite\r"

expect eof

Now try to run the Expect script with some parameters to see the output:

$ ./answerbot SomeName Programming

Awesome!! Now our automated Expect script is more dynamic.

Conditional Tests

You can write conditional tests using braces like this:

expect {

    "something" { send -- "send this\r" }

    "*another" { send -- "send another\r" }

}

We are going to change our script to return different conditions, and we will change our Expect script to handle those conditions.

We are going to emulate different expects with the following script:

#!/bin/bash

let number=$RANDOM

if [ $number -gt 25000 ]; then

	echo "What is your favorite topic?"

else

	echo "What is your favorite movie?"

fi

read $REPLY

When you run the script, it generates a random number every time, and based on that number; we put a condition to return different expects.

Let’s make out Expect script that will deal with that.

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect {

    "*topic?" { send -- "Programming\r" }

    "*movie?" { send -- "Star wars\r" }

}

expect eof

Very clear. If the script hits the topic output, the expect script will send programming, and if the script hits movie output, the expect script will send star wars. Isn’t cool?

If else Conditions

You can use if/else clauses in expect scripts like this:

#!/usr/bin/expect -f

set NUM 1

if { $NUM < 5 } {

    puts "\Smaller than 5\n"

} elseif { $NUM > 5 } {

    puts "\Bigger than 5\n"

} else {

    puts "\Equals 5\n"

}

Note: The opening brace must be on the same line.

While Loops

While loops in expect language must use braces to contain the expression like this:

#!/usr/bin/expect -f

set NUM 0

while { $NUM <= 5 } {

    puts "\nNumber is $NUM"

    set NUM [ expr $NUM + 1 ]

}

puts ""

For Loops

Like any scripting or programming language, you can use for loops for repetitive tasks, three fields must be specified, like the following format:

#!/usr/bin/expect -f

for {set NUM 0} {$NUM <= 5} {incr NUM} {

    puts "\nNUM = $NUM"

}

puts ""

User-defined Functions

You can define a function using proc like this:

proc myfunc { TOTAL } {

    set TOTAL [expr $TOTAL + 1]

    return "$TOTAL"

}

And you can use them after that.

#!/usr/bin/expect -f

proc myfunc { TOTAL } {

    set TOTAL [expr $TOTAL + 1]

    return "$TOTAL"

}

set NUM 0

while {$NUM <= 5} {

    puts "\nNumber $NUM"

    set NUM [myfunc $NUM]

}

puts ""

Interact Command

Sometimes your expect script contains some sensitive information that you don’t want to share with other users who use your expect scripts, like passwords or any other data. Hence, you want your script to take this password from you and continuing automation normally.

The interact command reverts the control to the keyboard.

When you use the interact command, expect will start reading from the keyboard.

This shell script will ask about the password as shown:

#!/bin/bash

echo "Hello, who are you?"

read $REPLY

echo "What is you password?"

read $REPLY

echo "What is your favorite topic?"

read $REPLY

Now we will write the Expect script that will prompt for the password:

#!/usr/bin/expect -f

set timeout -1

spawn ./questions

expect "Hello, who are you?\r"

send -- "Hi Im Adam\r"

expect "*password?\r"

interact ++ return

send "\r"

expect "*topic?\r"

send -- "Technology\r"

expect eof

After you type your password type ++ and the control will return from the keyboard to the script.

Expect language is ported to many languages like C#, Java, Perl, Python, Ruby, and Shell with almost the same concepts and syntax due to its simplicity and importance.

You can use the expect scripting language in quality assurance, network measurements such as echo response time, automate file transfers, updates, and many other uses.

I hope you now supercharged with some of the most important aspects of expect command, autoexpect command, and how to use it to automate your tasks in a smarter way.

Thank you.

Original article source at: https://likegeeks.com/

#linux #shell #bash #scripts #command #magic 

How to Automate Shell Scripts Like Magic using Expect Command

Чтение аргументов командной строки в Bash

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

Что такое аргументы командной строки в Bash

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

Как читать аргументы командной строки в Bash

Для изменения поведения скрипта в основном используются аргументы командной строки, которые включают опции или флаги. Например, у вас может быть сценарий, выполняющий операцию резервного копирования, и вы хотите включить параметр, указывающий папку назначения для резервной копии. Вот три способа чтения аргументов командной строки в сценарии bash:

  • Использование знака $
  • Использование сдвига
  • Использование команды getops

Как читать аргументы командной строки с помощью команды $ в Bash

Самый простой способ прочитать аргументы командной строки в Bash — использовать переменные $0, $1, $2 и т. д. Эти переменные представляют имя сценария ($0) и позиционные параметры, переданные сценарию ($1, $2 и т. д.). Вот пример кода bash, который использует команду $ для чтения аргументов командной строки:

#!/bin/bash

echo "Script name: $0"
echo "Argument1: $1"
echo "Argument2: $2"

Этот сценарий считывает аргументы командной строки в bash, используя переменные $0, $1 и $2. Переменная $0 содержит имя самого скрипта, а $1 и $2 содержат первый и второй аргументы командной строки соответственно, а для передачи аргументов скрипту используется следующий синтаксис:

<argument0……argumentN>

 Здесь имя файла может быть включено в качестве аргумента, если оно начинается с $0 и т. д. Этот скрипт считывает аргументы командной строки в Bash, используя переменные $0, $1 и $2. Переменная $0 содержит имя самого скрипта, а $1 и $2 содержат первый и второй аргументы командной строки соответственно, и ниже приведен вывод для него:

Как читать аргументы командной строки с помощью команды Shift в Bash

Команда «shift» в Bash позволяет сдвигать позиционные параметры влево, отбрасывая первый аргумент и перемещая остальные на одну позицию вниз. Это может быть полезно, если вам нужно обрабатывать аргументы в цикле или если вы хотите обрабатывать аргументы в определенном порядке. Вот пример:

!/bin/bash

echo "Script name: $0"

while [ "$#" -gt 0 ]; do
  echo "Argument1": $1
  shift
done

 Сценарий начинается с вывода имени сценария с использованием переменной $0, которая содержит имя сценария, вызванного из командной строки. Следующий раздел скрипта представляет собой цикл while, который проверяет, остались ли какие-либо аргументы командной строки для обработки. Он делает это, проверяя значение специальной переменной $#, которая содержит количество аргументов командной строки.

Затем цикл печатает текущий аргумент, используя переменную $1, содержащую первый аргумент, а затем использует команду shift для удаления первого аргумента из списка аргументов командной строки. Это сдвигает все оставшиеся аргументы на одну позицию вниз, так что $1 становится вторым аргументом, $2 становится третьим аргументом и так далее.

Как читать аргументы командной строки с помощью getopts

Команда «getopts» в Bash позволяет вам анализировать аргументы и параметры командной строки, это полезно, когда вам нужно указать дополнительные аргументы или флаги для вашего скрипта. Вот пример кода, который использует команду getopts и считывает два аргумента из командной строки:

#!/bin/bash

while getopts ":a:b:" opt; do
  case $opt in
    a) arg1="$OPTARG"
    ;;
    b) arg2="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done

echo "Argument 1: $arg1"
echo "Argument 2: $arg2"

 Команда getopts используется для перебора параметров и аргументов командной строки. Он принимает два аргумента: один представляет собой строку всех ожидаемых параметров, а другой — имя переменной, в которой будет храниться значение текущего обрабатываемого параметра.

В этом скрипте ожидаемыми параметрами являются -a и -b, за которыми следуют соответствующие аргументы. Команда getopts анализирует эти параметры и аргументы и присваивает их переменной $opt.

Затем оператор case используется для обработки каждой опции. Если опция -a, значение соответствующего аргумента присваивается переменной $arg1. Если указан параметр -b, значение соответствующего аргумента присваивается переменной $arg2. Если обнаружена недопустимая опция, на консоль выводится сообщение об ошибке.

После обработки всех параметров и аргументов скрипт выводит значения $arg1 и $arg2 в консоль с помощью команды echo. Вот результат кода:

Заключение

Аргументы командной строки в Bash используются для передачи параметров сценарию или команде, когда они выполняются из командной строки. Они могут включать значения, параметры или флаги, изменяющие поведение сценария, и необходимы для настройки поведения сценариев и команд Bash. Есть три способа чтения аргументов командной строки: использование знака $, использование команды getops и использование сдвига, и все они упомянуты в этом руководстве.

Оригинальный источник статьи: https://linuxhint.com/

#bash #command #line 

Чтение аргументов командной строки в Bash
津田  淳

津田 淳

1679412540

在 Bash 中读取命令行参数

使用 bash 脚本时,您可能会遇到需要通过命令行将参数传递给脚本的情况。在本文中,我们将探讨在 Bash 中读取命令行参数的不同方法,并提供每种方法的示例。

Bash 中的命令行参数是什么

bash 中的命令行参数是从命令行执行时传递给 bash 脚本或命令的参数。它们用于自定义脚本或命令的行为,并且可以包括脚本或命令用来执行特定任务的选项、标志或值。

如何在 Bash 中读取命令行参数

修改脚本的行为命令行参数主要用于包括选项或标志。例如,您可能有一个执行备份操作的脚本,并且您希望包含一个选项来指定备份的目标文件夹。以下是可以在 bash 脚本中读取命令行参数的三种方式:

  • 使用 $ 符号
  • 使用班次
  • 使用 getops 命令

如何在 Bash 中使用 $ 命令读取命令行参数

在 Bash 中读取命令行参数的最基本方法是使用变量 $0、$1、$2 等。这些变量代表脚本名称($0)和传递给脚本的位置参数($1、$2 等)。下面是一个使用 $ 命令读取命令行参数的示例 bash 代码:

#!/bin/bash

echo "Script name: $0"
echo "Argument1: $1"
echo "Argument2: $2"

此脚本使用 $0、$1 和 $2 变量读取 bash 中的命令行参数。$0 变量包含脚本本身的名称,而 $1 和 $2 分别包含第一个和第二个命令行参数,将参数传递给脚本的语法如下:

<argument0……argumentN>

 如果文件名从 $0 开始,则文件名可以作为参数包含在内,依此类推,此脚本使用 $0、$1 和 $2 变量读取 Bash 中的命令行参数。$0 变量包含脚本本身的名称,而 $1 和 $2 分别包含第一个和第二个命令行参数,下面是它的输出:

如何在 Bash 中使用 Shift 命令读取命令行参数

Bash 中的“shift”命令允许您将位置参数向左移动,丢弃第一个参数并将其余参数向下移动一个位置。如果您需要在循环中处理参数,或者如果您想按特定顺序处理参数,这将很有用。这是一个例子:

!/bin/bash

echo "Script name: $0"

while [ "$#" -gt 0 ]; do
  echo "Argument1": $1
  shift
done

 该脚本首先使用 $0 变量打印脚本名称,该变量包含从命令行调用的脚本名称。脚本的下一部分是一个 while 循环,它检查是否还有任何剩余的命令行参数需要处理。它通过检查特殊的 $# 变量的值来完成此操作,该变量包含命令行参数的数量。

然后循环使用包含第一个参数的 $1 变量打印当前参数,然后使用 shift 命令从命令行参数列表中删除第一个参数。这会将所有剩余的参数向下移动一个位置,因此 $1 成为第二个参数,$2 成为第三个参数,依此类推。

如何使用 getopts 读取命令行参数

Bash 中的“getopts”命令允许您解析命令行参数和选项,这在您需要为脚本提供可选参数或标志时很有用。下面是使用 getopts 命令并从命令行读取两个参数的示例代码:

#!/bin/bash

while getopts ":a:b:" opt; do
  case $opt in
    a) arg1="$OPTARG"
    ;;
    b) arg2="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done

echo "Argument 1: $arg1"
echo "Argument 2: $arg2"

 getopts 命令用于迭代命令行选项和参数。它有两个参数:一个是所有预期选项的字符串,另一个是将保存当前处理的选项值的变量名。

在此脚本中,预期的选项是 -a 和 -b,后跟相应的参数。getopts 命令解析这些选项和参数并将它们分配给 $opt 变量。

然后使用 case 语句处理每个选项。如果选项是 -a,相应参数的值将分配给 $arg1 变量。如果选项是 -b,相应参数的值将分配给 $arg2 变量。如果检测到无效选项,则会将错误消息打印到控制台。

处理完所有选项和参数后,脚本使用 echo 命令将 $arg1 和 $arg2 的值打印到控制台,这是代码的输出:

结论

Bash 中的命令行参数用于在从命令行执行时将参数传递给脚本或命令。它们可以包括修改脚本行为的值、选项或标志,并且对于自定义 Bash 脚本和命令的行为至关重要。有三种读取命令行参数的方法,它们是:使用 $ 符号、使用 getops 命令和使用 shift,所有这些都在本指南中提到。

文章原文出处:https: //linuxhint.com/

#bash #command #line 

在 Bash 中读取命令行参数
Bongani  Ngema

Bongani Ngema

1679408760

Read Command Line Arguments in a Bash

When working with bash scripting, you may encounter situations where you need to pass arguments to your script via the command line. In this article, we’ll explore the different ways to read command line arguments in Bash and provide examples of each method.

What are Command Line Arguments in Bash

Command line arguments in bash are the parameters that are passed to a bash script or command when it is executed from the command line. They are used to customize the behavior of the script or command, and can include options, flags, or values that are used by the script or command to perform specific tasks.

How to Read Command Line Arguments in a Bash

To modify the behavior of the script Command line arguments are mainly used that include options or flags. For example, you might have a script that performs a backup operation, and you want to include an option to specify the destination folder for the backup. Here are the three ways by which one can read command line arguments in bash script:

  • Using $ sign
  • Using shift
  • Using getops command

How to Read Command Line Arguments Using $ Command in Bash

The most basic way to read command line arguments in Bash is to use the variables $0, $1, $2, etc. These variables represent the script name ($0) and the positional parameters passed to the script ($1, $2, etc.). Here’s an example bash code that uses the $ command to read command line arguments:

#!/bin/bash

echo "Script name: $0"
echo "Argument1: $1"
echo "Argument2: $2"

This script reads command line arguments in bash using the $0, $1, and $2 variables. The $0 variable contains the name of the script itself, while $1 and $2 contain the first and second command line arguments, respectively and to pass arguments to the script here is the syntax:

<argument0……argumentN>

 Here the file name can be included as an argument if they start from $0 and so on, this script reads command line arguments in Bash using the $0, $1, and $2 variables. The $0 variable contains the name of the script itself, while $1 and $2 contain the first and second command line arguments, respectively and below is the output for it:

How to Read Command Line Arguments Using Shift Command in Bash

The “shift” command in Bash allows you to shift the positional parameters to the left, discarding the first argument and moving the rest down by one position. This can be useful if you need to process arguments in a loop or if you want to handle arguments in a specific order. Here’s an example:

!/bin/bash

echo "Script name: $0"

while [ "$#" -gt 0 ]; do
  echo "Argument1": $1
  shift
done

 The script starts by printing the name of the script using the $0 variable, which contains the name of the script as it was called from the command line. The next section of the script is a while loop that checks whether there are any remaining command line arguments to process. It does this by checking the value of the special $# variable, which contains the number of command line arguments.

The loop then prints the current argument using the $1 variable, which contains the first argument, and then uses the shift command to remove the first argument from the list of command line arguments. This shifts all the remaining arguments down by one position, so that $1 becomes the second argument, $2 becomes the third argument, and so on.

How to Read Command Line Arguments Using getopts

The “getopts’ command in Bash allows you to parse command line arguments and options, this is helpful when you need to give optional arguments or flags to your script. Here’s an example code that uses the getopts command and read two arguments from command line:

#!/bin/bash

while getopts ":a:b:" opt; do
  case $opt in
    a) arg1="$OPTARG"
    ;;
    b) arg2="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done

echo "Argument 1: $arg1"
echo "Argument 2: $arg2"

 The getopts command is used to iterate over the command line options and arguments. It takes two arguments: one is a string of all the expected options, and the other is the variable name that will hold the value of the currently processed option.

In this script, the expected options are -a and -b, which are followed by their corresponding arguments. The getopts command parses these options and arguments and assigns them to the $opt variable.

The case statement is then used to process each option. If the option is -a, the value of the corresponding argument is assigned to the $arg1 variable. If the option is -b, the value of the corresponding argument is assigned to the $arg2 variable. If an invalid option is detected, an error message is printed to the console.

After all options and arguments have been processed, the script prints the values of $arg1 and $arg2 to the console using the echo command, here is the output for the code:

Conclusion

Command line arguments in Bash are used to pass parameters to a script or command when it is executed from the command line. They can include values, options, or flags that modify the behavior of the script, and are essential for customizing the behavior of Bash scripts and commands. There are three ways to read command line arguments and those are: using $ sign, using getops command and using shift and all these are mentioned in this guide.

Original article source at: https://linuxhint.com/

#bash #command #line 

Read Command Line Arguments in a Bash
최  호민

최 호민

1679400600

초보자를 위한 Linux 셸 스크립트 및 명령줄

초보자를 위한 이 Bash 스크립팅 자습서에서는 Linux 셸 스크립트 및 명령줄에 대해 배웁니다. 변수, 명령, 입력/출력 및 디버깅을 포함하는 bash 스크립팅의 기본 사항을 배웁니다. 

Linux 에서 프로세스 자동화는 쉘 스크립팅 에 크게 의존합니다 . 여기에는 함께 실행할 수 있는 일련의 명령이 포함된 파일을 만드는 작업이 포함됩니다.

이 기사에서는 변수, 명령, 입력/출력 및 디버깅을 포함하는 bash 스크립팅 의 기본부터 시작합니다 . 우리는 또한 그 과정에서 각각의 예를 보게 될 것입니다.

시작하자. 🚀

목차

  • 전제 조건
  • 소개
    • Bash 스크립팅의 정의
    • Bash 스크립팅의 장점
    • Bash 셸 및 명령줄 인터페이스 개요
  • Bash 스크립팅을 시작하는 방법
    • 명령줄에서 Bash 명령을 실행하는 방법
    • Bash 스크립트를 만들고 실행하는 방법
  • Bash 스크립팅 기본 사항
    • bash 스크립팅의 주석
    • Bash의 변수 및 데이터 유형
    • Bash 스크립트의 입력 및 출력
    • 기본 Bash 명령(echo, read 등)
    • 조건문(if/else)
  • Bash에서 반복 및 분기
    • 루프 동안
    • for 루프
    • 사례 진술
  • 옥수수를 사용하여 스크립트를 예약하는 방법
  • Bash 스크립트를 디버깅하고 문제를 해결하는 방법
  • 결론
  • Bash 스크립팅에 대해 자세히 알아볼 수 있는 리소스

전제 조건

이 자습서를 따르려면 다음 액세스 권한이 있어야 합니다.

  • 명령줄에 액세스할 수 있는 실행 중인 Linux 버전입니다.

Linux가 설치되어 있지 않거나 막 시작한 경우 Replit을 통해 Linux 명령줄에 쉽게 액세스할 수 있습니다 . Replit은 몇 분 안에 bash 셸에 액세스할 수 있는 브라우저 기반 IDE입니다.

WSL(Linux용 Windows 하위 시스템)을 사용하여 Windows 시스템 위에 Linux를 설치할 수도 있습니다. 여기 에 대한 자습서가 있습니다.

소개

Bash 스크립팅의 정의

bash 스크립트는 bash 프로그램이 한 줄씩 실행하는 일련의 명령을 포함하는 파일입니다. 명령줄을 사용하여 특정 디렉터리 탐색, 폴더 생성, 프로세스 시작과 같은 일련의 작업을 수행할 수 있습니다.

이러한 명령을 스크립트에 저장하면 동일한 순서의 단계를 여러 번 반복하고 스크립트를 실행하여 실행할 수 있습니다.

Bash 스크립팅의 장점

Bash 스크립팅은 Unix/Linux 시스템에서 시스템 관리 작업 자동화, 시스템 리소스 관리 및 기타 일상적인 작업을 수행하기 위한 강력하고 다양한 도구입니다. 쉘 스크립팅의 장점은 다음과 같습니다.

  • 자동화 : 셸 스크립트를 사용하면 반복적인 작업과 프로세스를 자동화하여 시간을 절약하고 수동 실행으로 발생할 수 있는 오류 위험을 줄일 수 있습니다.
  • 이식성 : 셸 스크립트는 에뮬레이터 또는 가상 머신을 사용하여 Unix, Linux, macOS 및 Windows를 포함한 다양한 플랫폼 및 운영 체제에서 실행할 수 있습니다.
  • Flexibility: Shell scripts are highly customizable and can be easily modified to suit specific requirements. They can also be combined with other programming languages or utilities to create more powerful scripts.
  • Accessibility: Shell scripts are easy to write and don't require any special tools or software. They can be edited using any text editor, and most operating systems have a built-in shell interpreter.
  • Integration: Shell scripts can be integrated with other tools and applications, such as databases, web servers, and cloud services, allowing for more complex automation and system management tasks.
  • Debugging: Shell scripts are easy to debug, and most shells have built-in debugging and error-reporting tools that can help identify and fix issues quickly.

Bash 셸 및 명령줄 인터페이스 개요

"shell"과 "bash"라는 용어는 같은 의미로 사용됩니다. 그러나 둘 사이에는 미묘한 차이가 있습니다.

"셸"이라는 용어는 운영 체제와 상호 작용하기 위한 명령줄 인터페이스를 제공하는 프로그램을 나타냅니다. Bash(Bourne-Again SHell)는 가장 일반적으로 사용되는 Unix/Linux 셸 중 하나이며 많은 Linux 배포판의 기본 셸입니다.

셸 또는 명령줄 인터페이스는 다음과 같습니다.

이미지-135

쉘은 사용자의 명령을 수락하고 출력을 표시합니다.

위 출력에서 ​​는 zaira@Zaira쉘 프롬프트입니다. 쉘이 대화식으로 사용되는 경우 $사용자의 명령을 기다리고 있을 때 를 표시합니다.

셸이 루트(관리 권한이 있는 사용자)로 실행 중인 경우 프롬프트가 로 변경됩니다 #. 수퍼유저 셸 프롬프트는 다음과 같습니다.

[root@host ~]#

Bash는 일종의 셸이지만 Korn 셸(ksh), C 셸(csh) 및 Z 셸(zsh)과 같은 다른 셸도 사용할 수 있습니다. 각 셸에는 고유한 구문과 기능 집합이 있지만 모두 운영 체제와 상호 작용하기 위한 명령줄 인터페이스를 제공한다는 공통 목적을 공유합니다.

다음 명령을 사용하여 셸 유형을 확인할 수 있습니다 ps.

ps

나를 위한 결과는 다음과 같습니다.

이미지-134

쉘 유형을 확인합니다. 나는 bash 쉘을 사용하고 있습니다

요약하면 "쉘"은 명령줄 인터페이스를 제공하는 모든 프로그램을 가리키는 광범위한 용어인 반면 "Bash"는 유닉스/리눅스 시스템에서 널리 사용되는 특정 유형의 쉘입니다.

참고: 이 자습서에서는 "bash" 셸을 사용합니다.

Bash 스크립팅을 시작하는 방법

명령줄에서 Bash 명령 실행

앞에서 언급했듯이 쉘 프롬프트는 다음과 같습니다.

[username@host ~]$

기호 다음에 명령을 입력 $하고 터미널에서 출력을 볼 수 있습니다.

일반적으로 명령은 다음 구문을 따릅니다.

command [OPTIONS] arguments

몇 가지 기본 bash 명령에 대해 논의하고 출력을 살펴보겠습니다. 꼭 따라해보세요 :)

  • date: 현재 날짜를 표시합니다.
zaira@Zaira:~/shell-tutorial$ date
Tue Mar 14 13:08:57 PKT 2023
  • pwd: 현재 작업 디렉토리를 표시합니다.
zaira@Zaira:~/shell-tutorial$ pwd
/home/zaira/shell-tutorial
  • ls: 현재 디렉토리의 내용을 나열합니다.
zaira@Zaira:~/shell-tutorial$ ls
check_plaindrome.sh  count_odd.sh  env  log  temp
  • echo: 텍스트 문자열 또는 변수 값을 터미널에 인쇄합니다.
zaira@Zaira:~/shell-tutorial$ echo "Hello bash"
Hello bash

항상 명령과 함께 명령 설명서를 참조할 수 있습니다 man.

예를 들어 매뉴얼은 ls다음과 같습니다.

이미지-138

다음을 사용하여 명령에 대한 옵션을 자세히 볼 수 있습니다.man

How to Create and Execute Bash scripts

Script naming conventions

By naming convention, bash scripts end with .sh. However, bash scripts can run perfectly fine without the sh extension.

Adding the Shebang

Bash scripts start with a shebang. Shebang is a combination of bash # and bang ! followed by the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.

Below is an example of the shebang statement.

#!/bin/bash

You can find your bash shell path (which may vary from the above) using the command:

which bash

Creating our first bash script

Our first script prompts the user to enter a path. In return, its contents will be listed.

run_all.sh명령을 사용하여 이름이 지정된 파일을 만듭니다 vi. 원하는 편집기를 사용할 수 있습니다.

vi run_all.sh

파일에 다음 명령을 추가하고 저장합니다.

#!/bin/bash
echo "Today is " `date`

echo -e "\nenter the path to directory"
read the_path

echo -e "\n you path has the following files and folders: "
ls $the_path

사용자 제공 디렉토리의 내용을 인쇄하는 스크립트

스크립트를 한 줄씩 자세히 살펴보겠습니다. 동일한 스크립트를 다시 표시하지만 이번에는 줄 번호를 사용합니다.  

  1 #!/bin/bash
  2 echo "Today is " `date`
  3
  4 echo -e "\nenter the path to directory"
  5 read the_path
  6
  7 echo -e "\n you path has the following files and folders: "
  8 ls $the_path
  • 라인 #1: shebang( #!/bin/bash)은 bash 셸 경로를 가리킵니다.
  • 라인 #2: 이 echo명령은 터미널에 현재 날짜와 시간을 표시합니다. 는 date백틱 안에 있습니다.
  • 라인 #4: 사용자가 유효한 경로를 입력하기를 원합니다.
  • 라인 #5: 이 read명령은 입력을 읽고 변수에 저장합니다 the_path.
  • 줄 #8: 이 ls명령은 저장된 경로와 함께 변수를 가져와 현재 파일과 폴더를 표시합니다.

bash 스크립트 실행

스크립트를 실행 가능하게 만들려면 다음 명령을 사용하여 사용자에게 실행 권한을 할당하십시오.

chmod u+x run_all.sh

여기,

  • chmod현재 사용자의 파일 소유권을 수정합니다. u.
  • +x현재 사용자에게 실행 권한을 추가합니다. 이는 소유자인 사용자가 이제 스크립트를 실행할 수 있음을 의미합니다.
  • run_all.sh우리가 실행하려는 파일입니다.

언급된 방법 중 하나를 사용하여 스크립트를 실행할 수 있습니다.

  • sh run_all.sh
  • bash run_all.sh
  • ./run_all.sh

🚀 실행되는 것을 봅시다.

실행-스크립트-bash-2

 

Bash 스크립팅 기본 사항

bash 스크립팅의 주석

주석은 #bash 스크립팅에서 시작합니다. 즉, a로 시작하는 줄은 #주석이며 인터프리터에서 무시됩니다.

주석은 코드를 문서화하는 데 매우 유용하며 다른 사람들이 코드를 이해할 수 있도록 주석을 추가하는 것이 좋습니다.

다음은 주석의 예입니다.

# This is an example comment
# Both of these lines will be ignored by the interpreter

Bash의 변수 및 데이터 유형

Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.

There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.

In Bash, you can use and set the variable values in the following ways:

  1. Assign the value directly:
country=Pakistan

2.  Assign the value based on the output obtained from a program or command, using command substitution. Note that $ is required to access an existing variable's value.

same_country=$country

This assigns the value of countryto the new variable same_country

To access the variable value, append $ to the variable name.

zaira@Zaira:~$ country=Pakistan
zaira@Zaira:~$ echo $country
Pakistan
zaira@Zaira:~$ new_country=$country
zaira@Zaira:~$ echo $new_country
Pakistan

Assigning and printing variable values

 

Variable naming conventions

In Bash scripting, the following are the variable naming conventions:

  1. 변수 이름은 문자 또는 밑줄( _)로 시작해야 합니다.
  2. 변수 이름에는 문자, 숫자 및 밑줄( _)이 포함될 수 있습니다.
  3. 변수 이름은 대소문자를 구분합니다.
  4. 변수 이름에는 공백이나 특수 문자가 포함되어서는 안 됩니다.
  5. 변수의 목적을 반영하는 설명이 포함된 이름을 사용하십시오.
  6. if, then, else, fi등과 같은 예약어를 변수 이름으로 사용하지 마십시오 .

다음은 Bash에서 유효한 변수 이름의 몇 가지 예입니다.

name
count
_var
myVar
MY_VAR

다음은 유효하지 않은 변수 이름의 몇 가지 예입니다.

2ndvar (variable name starts with a number)
my var (variable name contains a space)
my-var (variable name contains a hyphen)

이러한 명명 규칙을 따르면 Bash 스크립트를 더 읽기 쉽고 유지하기 쉽게 만들 수 있습니다.

Bash 스크립트의 입력 및 출력

수집 입력

이 섹션에서는 스크립트에 입력을 제공하는 몇 가지 방법에 대해 설명합니다.

  1. 사용자 입력을 읽고 변수에 저장

명령을 사용하여 사용자 입력을 읽을 수 있습니다 read.

#!/bin/bash
echo "Today is " `date`

echo -e "\nenter the path to directory"
read the_path

echo -e "\nyour path has the following files and folders: "
ls $the_path

이름 쉬

2. 파일에서 읽기

이 코드는 명명된 파일에서 각 줄을 읽고 input.txt터미널에 인쇄합니다. 이 기사의 뒷부분에서 while 루프를 공부할 것입니다.

while read line
do
  echo $line
done < input.txt

3. 명령줄 인수

bash 스크립트 또는 함수에서 $1전달된 초기 인수, $2전달된 두 번째 인수 등을 나타냅니다.

이 스크립트는 이름을 명령줄 인수로 사용하고 개인화된 인사말을 인쇄합니다.

echo "Hello, $1!"

Zaira스크립트에 인수로 제공했습니다 .

#!/bin/bash
echo "Hello, $1!"

스크립트 코드:greeting.sh

산출:

이름-sh-1

출력 표시

여기에서는 스크립트에서 출력을 수신하는 몇 가지 방법에 대해 설명합니다.

  1. 터미널에 인쇄:
echo "Hello, World!"

그러면 "Hello, World!"라는 텍스트가 인쇄됩니다. 터미널로.

2. 파일에 쓰기:

echo "This is some text." > output.txt

This writes the text "This is some text." to a file named output.txt. Note that the >operator overwrites a file if it already has some content.

3.  Appending to a file:

echo "More text." >> output.txt

This appends the text "More text." to the end of the file output.txt.

4.  Redirecting output:

ls > files.txt

This lists the files in the current directory and writes the output to a file named files.txt. You can redirect output of any command to a file this way.

Basic Bash commands (echo, read, etc.)

Here is a list of some of the most commonly used bash commands:

  1. cd: Change the directory to a different location.
  2. ls: List the contents of the current directory.
  3. mkdir: Create a new directory.
  4. touch: Create a new file.
  5. rm: Remove a file or directory.
  6. cp: Copy a file or directory.
  7. mv: Move or rename a file or directory.
  8. echo: Print text to the terminal.
  9. cat: Concatenate and print the contents of a file.
  10. grep: Search for a pattern in a file.
  11. chmod: Change the permissions of a file or directory.
  12. sudo: Run a command with administrative privileges.
  13. df: Display the amount of disk space available.
  14. history: Show a list of previously executed commands.
  15. ps: Display information about running processes.

Conditional statements (if/else)

Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including if, if-else, if-elif-else, and nested conditionals.

Syntax:

if [[ condition ]];
then
	statement
elif [[ condition ]]; then
	statement 
else
	do this by default
fi

Syntax of bash conditional statements

We can use logical operators such as AND -a and OR -o to make comparisons that have more significance.

if [ $a -gt 60 -a $b -lt 100 ]

This statement checks if both conditions are true: a is greater than 60 AND b is less than 100.

Let's see an example of a Bash script that uses if, if-else, and if-elif-else statements to determine if a user-inputted number is positive, negative, or zero:

#!/bin/bash

echo "Please enter a number: "
read num

if [ $num -gt 0 ]; then
  echo "$num is positive"
elif [ $num -lt 0 ]; then
  echo "$num is negative"
else
  echo "$num is zero"
fi

Script to determine if a number is positive, negative, or zero

The script first prompts the user to enter a number. Then, it uses an if statement to check if the number is greater than 0. If it is, the script outputs that the number is positive. If the number is not greater than 0, the script moves on to the next statement, which is an if-elif statement. Here, the script checks if the number is less than 0. If it is, the script outputs that the number is negative. Finally, if the number is neither greater than 0 nor less than 0, the script uses an else statement to output that the number is zero.

Seeing it in action 🚀

테스트 홀수

Looping and Branching in Bash

While loop

While loops check for a condition and loop until the condition remains true. We need to provide a counter statement that increments the counter to control loop execution.

In the example below, (( i += 1 )) is the counter statement that increments the value of i. The loop will run exactly 10 times.

#!/bin/bash
i=1
while [[ $i -le 10 ]] ; do
   echo "$i"
  (( i += 1 ))
done

While loop that iterates 10 times.이미지-187

For loop

The for loop, just like the while loop, allows you to execute statements a specific number of times. Each loop differs in its syntax and usage.

In the example below, the loop will iterate 5 times.

#!/bin/bash

for i in {1..5}
do
    echo $i
done

For loop that iterates 5 times.이미지-186

Case statements

In Bash, case statements are used to compare a given value against a list of patterns and execute a block of code based on the first pattern that matches. The syntax for a case statement in Bash is as follows:

case expression in
    pattern1)
        # code to execute if expression matches pattern1
        ;;
    pattern2)
        # code to execute if expression matches pattern2
        ;;
    pattern3)
        # code to execute if expression matches pattern3
        ;;
    *)
        # code to execute if none of the above patterns match expression
        ;;
esac

Case statements syntax

여기서 "expression"은 비교하려는 값이고 "pattern1", "pattern2", "pattern3" 등은 비교하려는 패턴입니다.

이중 세미콜론 ";;" 각 패턴에 대해 실행할 각 코드 블록을 분리합니다. 별표 "*"는 지정된 패턴이 식과 일치하지 않는 경우 실행되는 기본 사례를 나타냅니다.

예를 보겠습니다.

fruit="apple"

case $fruit in
    "apple")
        echo "This is a red fruit."
        ;;
    "banana")
        echo "This is a yellow fruit."
        ;;
    "orange")
        echo "This is an orange fruit."
        ;;
    *)
        echo "Unknown fruit."
        ;;
esac

사례 진술의 예

이 예에서는 "fruit"의 값이 "apple"이므로 첫 번째 패턴이 일치하고 "This is a red fruit"를 에코하는 코드 블록이 일치합니다. 실행됩니다. "fruit" 값이 "banana"인 경우 두 번째 패턴이 일치하고 "This is a yellow fruit"를 에코하는 코드 블록이 일치합니다. 등을 실행합니다. "과일"의 값이 지정된 패턴과 일치하지 않으면 "알 수 없는 과일"을 에코하는 기본 사례가 실행됩니다.

cron을 사용하여 스크립트를 예약하는 방법

Cron은 Unix 계열 운영 체제에서 사용할 수 있는 작업 예약을 위한 강력한 유틸리티입니다. cron을 구성하여 매일, 매주, 매월 또는 특정 시간 기준으로 실행되도록 자동화된 작업을 설정할 수 있습니다. cron이 제공하는 자동화 기능은 Linux 시스템 관리에서 중요한 역할을 합니다.

다음은 cron을 예약하는 구문입니다.

# Cron job example
* * * * * sh /path/to/script.sh

여기서 *s는 각각 분(들) 시간(들) 일(들) 월(들) 평일(들)을 나타냅니다.

다음은 cron 작업 예약의 몇 가지 예입니다.

일정설명
0 0 * * *매일 자정에 스크립트 실행0 0 * * * /path/to/script.sh
*/5 * * * *5분마다 스크립트 실행*/5 * * * * /path/to/script.sh
0 6 * * 1-5월요일부터 금요일까지 오전 6시에 스크립트 실행0 6 * * 1-5 /path/to/script.sh
0 0 1-7 * *매월 첫 7일에 스크립트 실행0 0 1-7 * * /path/to/script.sh
0 12 1 * *매월 1일 정오에 스크립트 실행0 12 1 * * /path/to/script.sh

crontab 사용

crontab유틸리티는 cron 작업을 추가하고 편집하는 데 사용됩니다.

crontab -l특정 사용자에 대해 이미 예약된 스크립트를 나열합니다.

를 통해 cron을 추가하고 편집할 수 있습니다 crontab -e.

여기 내 다른 기사 에서 옥수수 작업에 대한 자세한 내용을 읽을 수 있습니다 .

Bash 스크립트를 디버깅하고 문제를 해결하는 방법

디버깅 및 문제 해결은 모든 Bash 스크립터에게 필수적인 기술입니다. Bash 스크립트는 매우 강력할 수 있지만 오류 및 예기치 않은 동작이 발생하기 쉽습니다. 이 섹션에서는 Bash 스크립트를 디버깅하고 문제를 해결하기 위한 몇 가지 팁과 기술에 대해 설명합니다.

옵션 설정set -x

One of the most useful techniques for debugging Bash scripts is to set the set -x option at the beginning of the script. This option enables debugging mode, which causes Bash to print each command that it executes to the terminal, preceded by a + sign. This can be incredibly helpful in identifying where errors are occurring in your script.

#!/bin/bash

set -x

# Your script goes here

Check the exit code

When Bash encounters an error, it sets an exit code that indicates the nature of the error. You can check the exit code of the most recent command using the $? variable. A value of 0 indicates success, while any other value indicates an error.

#!/bin/bash

# Your script goes here

if [ $? -ne 0 ]; then
    echo "Error occurred."
fi

Use echo statements

Bash 스크립트를 디버깅하는 또 다른 유용한 기술은 echo코드 전체에 명령문을 삽입하는 것입니다. 이를 통해 오류가 발생하는 위치와 변수에 전달되는 값을 식별할 수 있습니다.

#!/bin/bash

# Your script goes here

echo "Value of variable x is: $x"

# More code goes here

옵션 사용set -e

스크립트의 명령이 실패할 때 스크립트가 즉시 종료되도록 하려면 이 set -e옵션을 사용할 수 있습니다. 이 옵션을 사용하면 스크립트의 명령이 실패하면 Bash가 오류와 함께 종료되어 스크립트의 오류를 쉽게 식별하고 수정할 수 있습니다.

#!/bin/bash

set -e

# Your script goes here

로그를 확인하여 크론 문제 해결

로그 파일을 사용하여 크론 문제를 해결할 수 있습니다. 예약된 모든 작업에 대한 로그가 유지됩니다. 특정 작업이 의도한 대로 실행되었는지 로그에서 확인하고 확인할 수 있습니다.

Ubuntu/Debian의 경우 다음에서 로그를 찾을 수 있습니다 cron.

/var/log/syslog

위치는 다른 배포판에 따라 다릅니다.

cron 작업 로그 파일은 다음과 같습니다.

2022-03-11 00:00:01 Task started
2022-03-11 00:00:02 Running script /path/to/script.sh
2022-03-11 00:00:03 Script completed successfully
2022-03-11 00:05:01 Task started
2022-03-11 00:05:02 Running script /path/to/script.sh
2022-03-11 00:05:03 Error: unable to connect to database
2022-03-11 00:05:03 Script exited with error code 1
2022-03-11 00:10:01 Task started
2022-03-11 00:10:02 Running script /path/to/script.sh
2022-03-11 00:10:03 Script completed successfully

크론 로그

결론

이 기사에서는 터미널에 액세스하는 방법부터 시작한 다음 몇 가지 기본 bash 명령을 실행했습니다. 우리는 또한 bash 쉘이 무엇인지 연구했습니다. 루프와 조건문을 사용하여 코드를 분기하는 방법을 간단히 살펴보았습니다. 마지막으로 cron을 사용한 스크립트 자동화와 몇 가지 문제 해결 기술에 대해 논의했습니다.

Bash 스크립팅에 대해 자세히 알아볼 수 있는 리소스

bash 스크립팅의 세계를 더 깊이 파고들고 싶다면 freeCodeCamp에서 Linux에 대한 6시간 과정을 살펴보는 것이 좋습니다.

이 튜토리얼에서 배운 것 중 가장 좋아하는 것은 무엇입니까? 또한 이러한 플랫폼 중 어느 곳에서나 저와 연결할 수 있습니다 . 📧�

다음 튜토리얼에서 만나요, 행복한 코딩하세요 😁

배너 이미지 크레딧: Image by Freepik

출처: https://www.freecodecamp.org

#linux

초보자를 위한 Linux 셸 스크립트 및 명령줄

Linux Shell Script and Command Line for Beginners

In this Bash Scripting tutorial for beginners, you'll learn about Linux Shell Script and Command Line. Learn the basics of bash scripting which includes variables, commands, inputs/ outputs, and debugging. 

In Linux, process automation relies heavily on shell scripting. This involves creating a file containing a series of commands that can be executed together.

In this article, we'll start with the basics of bash scripting which includes variables, commands, inputs/ outputs, and debugging. We'll also see examples of each along the way.

Let's get started. 🚀

Table of Contents

  • Pre-requisites
  • Introduction
    • Definition of Bash scripting
    • Advantages of Bash scripting
    • Overview of Bash shell and command line interface
  • How to Get Started with Bash Scripting
    • How to Run Bash Commands from the Command Line
    • How to Create and Execute Bash Scripts
  • Bash Scripting Basics
    • Comments in bash scripting
    • Variables and data types in Bash
    • Input and output in Bash scripts
    • Basic Bash commands (echo, read, etc.)
    • Conditional statements (if/else)
  • Looping and Branching in Bash
    • While loop
    • For loop
    • Case statements
  • How to Schedule Scripts using corn
  • How to Debug and Troubleshoot Bash Scripts
  • Conclusion
  • Resources for learning more about Bash scripting

Pre-requisites

To follow along with this tutorial, you should have the following accesses:

  • A running version of Linux with access to the command line.

If you do not have Linux installed or you are just starting out, you can easily access the Linux command line through Replit. Replit is a browser-based IDE where you can access the bash shell in a few minutes.

You can also install Linux on top of your Windows system using WSL (Windows Subsystem for Linux). Here is a tutorial for that.

Introduction

Definition of Bash scripting

A bash script is a file containing a sequence of commands that are executed by the bash program line by line. It allows you to perform a series of actions, such as navigating to a specific directory, creating a folder, and launching a process using the command line.

By saving these commands in a script, you can repeat the same sequence of steps multiple times and execute them by running the script.

Advantages of Bash scripting

Bash scripting is a powerful and versatile tool for automating system administration tasks, managing system resources, and performing other routine tasks in Unix/Linux systems. Some advantages of shell scripting are:

  • Automation: Shell scripts allow you to automate repetitive tasks and processes, saving time and reducing the risk of errors that can occur with manual execution.
  • Portability: Shell scripts can be run on various platforms and operating systems, including Unix, Linux, macOS, and even Windows through the use of emulators or virtual machines.
  • Flexibility: Shell scripts are highly customizable and can be easily modified to suit specific requirements. They can also be combined with other programming languages or utilities to create more powerful scripts.
  • Accessibility: Shell scripts are easy to write and don't require any special tools or software. They can be edited using any text editor, and most operating systems have a built-in shell interpreter.
  • Integration: Shell scripts can be integrated with other tools and applications, such as databases, web servers, and cloud services, allowing for more complex automation and system management tasks.
  • Debugging: Shell scripts are easy to debug, and most shells have built-in debugging and error-reporting tools that can help identify and fix issues quickly.

Overview of Bash shell and command line interface

The terms "shell" and "bash" are used interchangeably. But there is a subtle difference between the two.

The term "shell" refers to a program that provides a command-line interface for interacting with an operating system. Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux shells and is the default shell in many Linux distributions.

A shell or command-line interface looks like this:

image-135

The shell accepts commands from the user and displays the output

In the above output, zaira@Zaira is the shell prompt. When a shell is used interactively, it displays a $ when it is waiting for a command from the user.

If the shell is running as root (a user with administrative rights), the prompt is changed to #. The superuser shell prompt looks like this:

[root@host ~]#

Although Bash is a type of shell, there are other shells available as well, such as Korn shell (ksh), C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all share the common purpose of providing a command-line interface for interacting with the operating system.

You can determine your shell type using the ps command:

ps

Here is the output for me:

image-134

Checking the shell type. I'm using bash shell

In summary, while "shell" is a broad term that refers to any program that provides a command-line interface, "Bash" is a specific type of shell that is widely used in Unix/Linux systems.

Note: In this tutorial, we will be using the "bash" shell.

How to Get Started with Bash Scripting

Running Bash commands from the command line

As mentioned earlier, the shell prompt looks something like this:

[username@host ~]$

You can enter any command after the $ sign and see the output on the terminal.

Generally, commands follow this syntax:

command [OPTIONS] arguments

Let's discuss a few basic bash commands and see their outputs. Make sure to follow along :)

  • date: Displays the current date
zaira@Zaira:~/shell-tutorial$ date
Tue Mar 14 13:08:57 PKT 2023
  • pwd: Displays the present working directory.
zaira@Zaira:~/shell-tutorial$ pwd
/home/zaira/shell-tutorial
  • ls: Lists the contents of the current directory.
zaira@Zaira:~/shell-tutorial$ ls
check_plaindrome.sh  count_odd.sh  env  log  temp
  • echo: Prints a string of text, or value of a variable to the terminal.
zaira@Zaira:~/shell-tutorial$ echo "Hello bash"
Hello bash

You can always refer to a commands manual with the man command.

For example, the manual for ls looks something like this:

image-138

You can see options for a command in detail using man

How to Create and Execute Bash scripts

Script naming conventions

By naming convention, bash scripts end with .sh. However, bash scripts can run perfectly fine without the sh extension.

Adding the Shebang

Bash scripts start with a shebang. Shebang is a combination of bash # and bang ! followed by the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.

Below is an example of the shebang statement.

#!/bin/bash

You can find your bash shell path (which may vary from the above) using the command:

which bash

Creating our first bash script

Our first script prompts the user to enter a path. In return, its contents will be listed.

Create a file named run_all.sh using the vi command. You can use any editor of your choice.

vi run_all.sh

Add the following commands in your file and save it:

#!/bin/bash
echo "Today is " `date`

echo -e "\nenter the path to directory"
read the_path

echo -e "\n you path has the following files and folders: "
ls $the_path

Script to print contents of a user supplied directory

Let's take a deeper look at the script line by line. I am displaying the same script again, but this time with line numbers.  

  1 #!/bin/bash
  2 echo "Today is " `date`
  3
  4 echo -e "\nenter the path to directory"
  5 read the_path
  6
  7 echo -e "\n you path has the following files and folders: "
  8 ls $the_path
  • Line #1: The shebang (#!/bin/bash) points toward the bash shell path.
  • Line #2: The echo command is displaying the current date and time on the terminal. Note that the date is in backticks.
  • Line #4: We want the user to enter a valid path.
  • Line #5: The read command reads the input and stores it in the variable the_path.
  • line #8: The ls command takes the variable with the stored path and displays the current files and folders.

Executing the bash script

To make the script executable, assign execution rights to your user using this command:

chmod u+x run_all.sh

Here,

  • chmod modifies the ownership of a file for the current user :u.
  • +x adds the execution rights to the current user. This means that the user who is the owner can now run the script.
  • run_all.sh is the file we wish to run.

You can run the script using any of the mentioned methods:

  • sh run_all.sh
  • bash run_all.sh
  • ./run_all.sh

Let's see it running in action 🚀

run-script-bash-2

 

Bash Scripting Basics

Comments in bash scripting

Comments start with a # in bash scripting. This means that any line that begins with a # is a comment and will be ignored by the interpreter.

Comments are very helpful in documenting the code, and it is a good practice to add them to help others understand the code.

These are examples of comments:

# This is an example comment
# Both of these lines will be ignored by the interpreter

Variables and data types in Bash

Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.

There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.

In Bash, you can use and set the variable values in the following ways:

  1. Assign the value directly:
country=Pakistan

2.  Assign the value based on the output obtained from a program or command, using command substitution. Note that $ is required to access an existing variable's value.

same_country=$country

This assigns the value of countryto the new variable same_country

To access the variable value, append $ to the variable name.

zaira@Zaira:~$ country=Pakistan
zaira@Zaira:~$ echo $country
Pakistan
zaira@Zaira:~$ new_country=$country
zaira@Zaira:~$ echo $new_country
Pakistan

Assigning and printing variable values

 

Variable naming conventions

In Bash scripting, the following are the variable naming conventions:

  1. Variable names should start with a letter or an underscore (_).
  2. Variable names can contain letters, numbers, and underscores (_).
  3. Variable names are case-sensitive.
  4. Variable names should not contain spaces or special characters.
  5. Use descriptive names that reflect the purpose of the variable.
  6. Avoid using reserved keywords, such as if, then, else, fi, and so on as variable names.

Here are some examples of valid variable names in Bash:

name
count
_var
myVar
MY_VAR

And here are some examples of invalid variable names:

2ndvar (variable name starts with a number)
my var (variable name contains a space)
my-var (variable name contains a hyphen)

Following these naming conventions helps make Bash scripts more readable and easier to maintain.

Input and output in Bash scripts

Gathering input

In this section, we'll discuss some methods to provide input to our scripts.

  1. Reading the user input and storing it in a variable

We can read the user input using the read command.

#!/bin/bash
echo "Today is " `date`

echo -e "\nenter the path to directory"
read the_path

echo -e "\nyour path has the following files and folders: "
ls $the_path

name-sh

2.  Reading from a file

This code reads each line from a file named input.txt and prints it to the terminal. We'll study while loops later in this article.

while read line
do
  echo $line
done < input.txt

3.  Command line arguments

In a bash script or function, $1 denotes the initial argument passed, $2 denotes the second argument passed, and so forth.

This script takes a name as a command-line argument and prints a personalized greeting.

echo "Hello, $1!"

We have supplied Zaira as our argument to the script.

#!/bin/bash
echo "Hello, $1!"

The code for the script: greeting.sh

Output:

name-sh-1

Displaying output

Here we'll discuss some methods to receive output from the scripts.

  1. Printing to the terminal:
echo "Hello, World!"

This prints the text "Hello, World!" to the terminal.

2.  Writing to a file:

echo "This is some text." > output.txt

This writes the text "This is some text." to a file named output.txt. Note that the >operator overwrites a file if it already has some content.

3.  Appending to a file:

echo "More text." >> output.txt

This appends the text "More text." to the end of the file output.txt.

4.  Redirecting output:

ls > files.txt

This lists the files in the current directory and writes the output to a file named files.txt. You can redirect output of any command to a file this way.

Basic Bash commands (echo, read, etc.)

Here is a list of some of the most commonly used bash commands:

  1. cd: Change the directory to a different location.
  2. ls: List the contents of the current directory.
  3. mkdir: Create a new directory.
  4. touch: Create a new file.
  5. rm: Remove a file or directory.
  6. cp: Copy a file or directory.
  7. mv: Move or rename a file or directory.
  8. echo: Print text to the terminal.
  9. cat: Concatenate and print the contents of a file.
  10. grep: Search for a pattern in a file.
  11. chmod: Change the permissions of a file or directory.
  12. sudo: Run a command with administrative privileges.
  13. df: Display the amount of disk space available.
  14. history: Show a list of previously executed commands.
  15. ps: Display information about running processes.

Conditional statements (if/else)

Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including if, if-else, if-elif-else, and nested conditionals.

Syntax:

if [[ condition ]];
then
	statement
elif [[ condition ]]; then
	statement 
else
	do this by default
fi

Syntax of bash conditional statements

We can use logical operators such as AND -a and OR -o to make comparisons that have more significance.

if [ $a -gt 60 -a $b -lt 100 ]

This statement checks if both conditions are true: a is greater than 60 AND b is less than 100.

Let's see an example of a Bash script that uses if, if-else, and if-elif-else statements to determine if a user-inputted number is positive, negative, or zero:

#!/bin/bash

echo "Please enter a number: "
read num

if [ $num -gt 0 ]; then
  echo "$num is positive"
elif [ $num -lt 0 ]; then
  echo "$num is negative"
else
  echo "$num is zero"
fi

Script to determine if a number is positive, negative, or zero

The script first prompts the user to enter a number. Then, it uses an if statement to check if the number is greater than 0. If it is, the script outputs that the number is positive. If the number is not greater than 0, the script moves on to the next statement, which is an if-elif statement. Here, the script checks if the number is less than 0. If it is, the script outputs that the number is negative. Finally, if the number is neither greater than 0 nor less than 0, the script uses an else statement to output that the number is zero.

Seeing it in action 🚀

test-odd

Looping and Branching in Bash

While loop

While loops check for a condition and loop until the condition remains true. We need to provide a counter statement that increments the counter to control loop execution.

In the example below, (( i += 1 )) is the counter statement that increments the value of i. The loop will run exactly 10 times.

#!/bin/bash
i=1
while [[ $i -le 10 ]] ; do
   echo "$i"
  (( i += 1 ))
done

While loop that iterates 10 times.image-187

For loop

The for loop, just like the while loop, allows you to execute statements a specific number of times. Each loop differs in its syntax and usage.

In the example below, the loop will iterate 5 times.

#!/bin/bash

for i in {1..5}
do
    echo $i
done

For loop that iterates 5 times.image-186

Case statements

In Bash, case statements are used to compare a given value against a list of patterns and execute a block of code based on the first pattern that matches. The syntax for a case statement in Bash is as follows:

case expression in
    pattern1)
        # code to execute if expression matches pattern1
        ;;
    pattern2)
        # code to execute if expression matches pattern2
        ;;
    pattern3)
        # code to execute if expression matches pattern3
        ;;
    *)
        # code to execute if none of the above patterns match expression
        ;;
esac

Case statements syntax

Here, "expression" is the value that we want to compare, and "pattern1", "pattern2", "pattern3", and so on are the patterns that we want to compare it against.

The double semicolon ";;" separates each block of code to execute for each pattern. The asterisk "*" represents the default case, which executes if none of the specified patterns match the expression.

Let's see an example.

fruit="apple"

case $fruit in
    "apple")
        echo "This is a red fruit."
        ;;
    "banana")
        echo "This is a yellow fruit."
        ;;
    "orange")
        echo "This is an orange fruit."
        ;;
    *)
        echo "Unknown fruit."
        ;;
esac

Example of case statement

In this example, since the value of "fruit" is "apple", the first pattern matches, and the block of code that echoes "This is a red fruit." is executed. If the value of "fruit" were instead "banana", the second pattern would match and the block of code that echoes "This is a yellow fruit." would execute, and so on. If the value of "fruit" does not match any of the specified patterns, the default case is executed, which echoes "Unknown fruit."

How to Schedule Scripts using cron

Cron is a powerful utility for job scheduling that is available in Unix-like operating systems. By configuring cron, you can set up automated jobs to run on a daily, weekly, monthly, or specific time basis. The automation capabilities provided by cron play a crucial role in Linux system administration.

Below is the syntax to schedule crons:

# Cron job example
* * * * * sh /path/to/script.sh

Here, the *s represent minute(s) hour(s) day(s) month(s) weekday(s), respectively.

Below are some examples of scheduling cron jobs.

SCHEDULEDESCRIPTIONEXAMPLE
0 0 * * *Run a script at midnight every day0 0 * * * /path/to/script.sh
*/5 * * * *Run a script every 5 minutes*/5 * * * * /path/to/script.sh
0 6 * * 1-5Run a script at 6 am from Monday to Friday0 6 * * 1-5 /path/to/script.sh
0 0 1-7 * *Run a script on the first 7 days of every month0 0 1-7 * * /path/to/script.sh
0 12 1 * *Run a script on the first day of every month at noon0 12 1 * * /path/to/script.sh

Using crontab

The crontab utility is used to add and edit the cron jobs.

crontab -l lists the already scheduled scripts for a particular user.

You can add and edit the cron through crontab -e.

You can read more about corn jobs in my other article here.

How to Debug and Troubleshoot Bash Scripts

Debugging and troubleshooting are essential skills for any Bash scripter. While Bash scripts can be incredibly powerful, they can also be prone to errors and unexpected behavior. In this section, we will discuss some tips and techniques for debugging and troubleshooting Bash scripts.

Set the set -x option

One of the most useful techniques for debugging Bash scripts is to set the set -x option at the beginning of the script. This option enables debugging mode, which causes Bash to print each command that it executes to the terminal, preceded by a + sign. This can be incredibly helpful in identifying where errors are occurring in your script.

#!/bin/bash

set -x

# Your script goes here

Check the exit code

When Bash encounters an error, it sets an exit code that indicates the nature of the error. You can check the exit code of the most recent command using the $? variable. A value of 0 indicates success, while any other value indicates an error.

#!/bin/bash

# Your script goes here

if [ $? -ne 0 ]; then
    echo "Error occurred."
fi

Use echo statements

Another useful technique for debugging Bash scripts is to insert echo statements throughout your code. This can help you identify where errors are occurring and what values are being passed to variables.

#!/bin/bash

# Your script goes here

echo "Value of variable x is: $x"

# More code goes here

Use the set -e option

If you want your script to exit immediately when any command in the script fails, you can use the set -e option. This option will cause Bash to exit with an error if any command in the script fails, making it easier to identify and fix errors in your script.

#!/bin/bash

set -e

# Your script goes here

Troubleshooting crons by verifying logs

We can troubleshoot crons using the log files. Logs are maintained for all the scheduled jobs. You can check and verify in logs if a specific job ran as intended or not.

For Ubuntu/Debian, you can find cronlogs at:

/var/log/syslog

The location varies for other distributions.

A cron job log file can look like this:

2022-03-11 00:00:01 Task started
2022-03-11 00:00:02 Running script /path/to/script.sh
2022-03-11 00:00:03 Script completed successfully
2022-03-11 00:05:01 Task started
2022-03-11 00:05:02 Running script /path/to/script.sh
2022-03-11 00:05:03 Error: unable to connect to database
2022-03-11 00:05:03 Script exited with error code 1
2022-03-11 00:10:01 Task started
2022-03-11 00:10:02 Running script /path/to/script.sh
2022-03-11 00:10:03 Script completed successfully

Cron log

Conclusion

In this article, we started with how to access the terminal and then ran some basic bash commands. We also studied what a bash shell is. We briefly looked at branching the code using loops and conditionals. Finally, we discussed automating the scripts using cron followed by some troubleshooting techniques.

Resources for learning more about Bash scripting

If you want to dig deeper into the world of bash scripting, I would suggest you have a look at this 6-hour course on Linux at freeCodeCamp.

What’s your favorite thing you learned from this tutorial? You can also connect with me on any of these platforms. 📧�

See you in the next tutorial, happy coding 😁

Banner image credits: Image by Freepik

Source: https://www.freecodecamp.org

#linux #bash #commandline

Linux Shell Script and Command Line for Beginners