Что такое bash в linux
Перейти к содержимому

Что такое bash в linux

  • автор:

What is a shell?

Traditionally, when you log into a Unix system, the system would start one program for you. That program is a shell, i.e., a program designed to start other programs. It’s a command line shell: you start another program by typing its name.

Simply put, the shell is a a command language interpreter that takes commands in English from the keyboard and gives them to the operating system to perform. Shell is not part of system kernel, but uses the system kernel to execute programs, create files etc. It provides an interface to an Operating System. The shell is only one layer above the OS,

In the old days, it was the only user interface available on a Unix-like system such as Linux. Nowadays, most users prefer the graphical user interface (GUI) offered by operating systems such as Windows, Linux and macOS. Most current Unix-based systems offer both a command line interface (CLI) such as the shell and a graphical user interface.

Two well-known shells are Windows shell and Bash for Linux and macOS.

Shells may be used interactively or non-interactively. As the term implies, interactive means that the commands are run with user-interaction from keyboard. e.g. the shell can prompt the user to enter input from the keyboard. When executing non-interactively, shells execute commands read from a file.

What is a bash?

Bash is a type of interpreter that processes shell commands. A shell interpreter takes commands in plain text format and calls Operating System services to do something.

It stands for Bourne Again Shell, an enhanced version of the original Unix shell program, sh , written by Steve Bourne and it is the default shell on many Linux distributions today. Besides bash , there are other shell programs that can be installed in a Linux system. These include: Korn shell ( ksh ), enhanced C shell ( tcsh ), friendly interactive shell ( fish ) and Z-shell zsh . Note that each shell does the same job, but each understand a different command syntax and provides different built-in functions.

bash and sh are two different shells. Basically bash is sh , with more features and better syntax. Most commands work the same, but they are different.

Bash is one of the popular command-line shells, programs whose main job is to start other programs (in addition to some auxiliary functions). The command-line part means you control it by typing commands one line at a time. Properly speaking, a graphical user interface (GUI) you use to start programs by double-clicking on icons is also a shell, but in practice by “shell” people mostly mean command-line ones.

Windows Command Line (CMD) vs. Mac OS Terminal

Three big Operating Systems exist: (1) MacOS, (2) Windows, and (3) Linux

Mac Terminal which runs UNIX commands whereas Windows Command Line is based on MS-DOS System commands.

Every operating system has options for selecting the shell. Mac Terminal uses derivatives of sh . bash was default on MacOS until 10.15 (Catalina). zsh is default in 10.15. All sh programs have the same basic syntax. However, both are trying to solve the same problems.

bash and sh (written by Steve Bourne) are two different shells. Basically bash is sh , with more features and better syntax.

MacOS uses bash (Bourne Again SHell), while Windows uses cmd.exe and PowerShell. bash , cmd.exe and PowerShell all have their own unique syntax. PowerShell is only preinstalled on Windows 7 and onwards.

You can replace bash with zsh , ksh , and a variety of other shells in MacOS and Linux. You can’t do this in Windows OS.

Most Linux distributions also come with bash as the default shell. Besides bash , there are other shell programs that can be installed in a Linux system. These include: Korn shell ( ksh ), enhanced C shell ( tcsh ), friendly interactive shell ( fish ) and Z-shell ( zsh ).

To access the Unix command prompt in Mac OS X, open the Terminal application. It is located by default inside the Utilities folder, which in turn is inside the Applications folder, i.e., /Applications/Utilities/ folder. To access the command prompt in Windows, in Windows 7, click the Start button and enter cmd . In other versions, from the Start menu, select Run… and then enter cmd .

In order to see the differences between MacOS and Windows commands, see this PDF file: https://enexdi.sciencesconf.org/data/pages/windows_vs_mac_commands_1.pdf

What’s a “Terminal?”

Terminal is a program that provides a graphical interface between the shell and the user. It receives from the shell e.g. the characters “command not found” and figures out how to display them to you — with what font, where on the screen, in what colour, whether there should be a scrollbar. When you press some keys, it figures out whether to send them on to the shell as characters (e.g. ls -l ), or to interpret them on its own (e.g. ⌘C ).

When you open the Terminal app, it automatically opens a shell to connect you to. In its settings, you could choose a different shell from Bash.

What is a command?

A “command” is a line that tells the terminal to perform an action. For example:

Another example: echo perform an action to print hellp on screen

Another example: say will read whatever string you write on terminal.

There are three rules of commands:

  1. A command can act alone. For example, date can act alone, you do not need to write anything else.
  2. A command can act on something. For example, echo command can act on a string. It does not act alone.
  3. A command can have Options which let the command perform its action in a different way. For example, using command date giving time in UTC time zone:
So, how do you type commands?

The syntax of commands is given in the following:

if you add -n option, it will not print in a new line.

A couple of other examples:

  • killall : For example, turn on Mac browser Safari and on terminal, do killall Safari , it will close the Safari application.
  • cal can act alone or on something.

will give directly current date and month which is 30th of March.

Some common commands

whoami will print your username on your computer:

pwd will print the present working directory:

ls will print what is insider the current folder, standing for “list”:

ls -a will return all the hidden files. Hidden files usually start with a dot (.).

ls -l will print details of the visible files in the current folder.

Let’s inspect a file after printing using this command

  • Every file or folder has a name ( Zoom )
  • It will also print when the file last edited or created ( Mar 26 11:45 )
  • Every file or folder has a size ( 128 )
  • Every file or directory belongs to some user (owner) ( mustafamuratarat )
  • Every file or directory is assigned to some group which contains one or more users ( staff )
  • It will also print number of links this file has ( 4 )
  • Files can be Readable (r), Writable (w) or Executable (Accessable) (x) ( drwxr-xr-x@ ).

Let’s look at the first character. The first character identifies the file type: d means directory which means a folder. — means that this line is a regular file.

The rest of this line is divided by into three groups. They describe the permissions on the file. The first three rwx , the second three r-x and the last three r-x . The first three characters refer to the owner of the file. They are telling us the owner ( mustafamuratarat ) can read, write and execute the file. The second three characters refer to the group which this folder is assigned to. They are telling us that this folder is the group stuff can read and execute. They cannot write because there is no w . The third group of three characters refer to everyone else (or world). They can read and execute but cannot write.

Sometimes there are the three dashes (—) meaning that they have no permissions at all regarding the file. There’s a dash where the r normally appears, so they cannot even read it. The dashes afterward tell you they cannot write to the file or execute it. If they try to do anything with the file, they will get a “permission denied” error.

clear will clear the screen of the terminal.

You can also see what’s inside of a folder without going to that folder by just assigning the path. My home directory has Desktop folder. Without changing the directory, I can see what’s insider the desktop folder using the command ls Desktop/ .

I can also find some information about a file using file command:

We can change the current directory using the command cd .

Now, what this actually means is that if we are currently in directory /home/kt/abc and now you can use .. as an argument to cd to move to the parent directory /home/kt as :

For an example, let’s say our home directory is /Users/mustafamuratarat and we are in /Users/mustafamuratarat/Desktop :

Additionally, whichever folder you are in, you can just type cd and it will take you back to the home directory.

Let’s say that I am in the folder called spark_book which is inside spark folder which is in Desktop directory.

cd directly takes me back to home directory which is /Users/mustafamuratarat .

Again, we are in the folder Desktop/spark/spark_book . If we want to go back two-steps back which is Desktop folder but not to home directory:

open will open whichever file you call.

will open the pdf file test.txtf .

touch command will create a file. You will provide the extension.

will create an Excel file named Untitled_test .


mkdir will create a new folder, stands for “make directory”.

First let’s create a new folder named newfolder and inside this folder, let’s create some files and folders.

What if you want to create a new directory and, at the same time, create a new directory to contain it?

Command mkdir will not work because newfolder2 does not even exist. Simply use the -p command option. The following command will create a new folder called newfolder2 and, at the same time, create a directory within newfolder2 called newfolder :

mv will move a file (or a folder) or quickly rename it.

will rename the file a.txt to aaa.txt .

will rename the folder (directory) A-folder as A-renamed-folder .

Additionally, the command below

will move the file aaa.txt from newfolder to A-folder .

cp will make copy of the existing file.

We are in folder newfolder . Let’s add some text in 1.txt using nano .

Let’s make a copy of 1.txt to another file 1a.txt .

This will result in two identical files: one called 1.txt and one called 1a.txt .

will copy the file a.html into the folder A-folder .

rm command will remove a file.

The first two commands will remove the files 2.txt and a.html from folder newfolder and the last command will remove a.html insider the folder A-folder .

In some instances, you’ll be asked to confirm the deletion after you issue the command. If you want to delete a file without being asked to confirm it, type the following: rm –f myfile .

The -f option stands for force (that is, force the deletion).

* practically means zero or more characters.

rm -rf will remove a directory.

So, you can type rm –f * to delete all files within a directory, or type rm –f myfile* to delete all files that start with the word myfile . But be careful with the rm command. Keep in mind that you cannot salvage files easily if you accidentally delete them!

One important command-line option is -r . This stands for recursive and tells BASH that you want to compy a directory and its contents (as well as any directories within this directory). Only a handful of BASH commands default to recursive copying. rm command needs -R option if there are some files inside the folder to be removed. Similar case is valid for cp . However, mv command does not need such an option.

For example, ls -R . will recursively list all the files inside the working directory and also, files of other folders inside the current directory.

A-folder , B-folder and C-folder is empty.


If, at the command prompt, you try to copy, move or otherwise manipulate files that have spaces in their names, you’ll run into problems. For example, suppose you want to move the file picture from germany.jpg to the directory mydirectory. In theory the following command should do the trick:

But you will get the following error:

There are two solutions. The easiest is to enclose the filename in quotation marks (“), so the previous command would read as follows:

The other solution is to precede each space with a backslash. This tells BASH you’re including a literal character in the filename. In other words, you’re telling BASH not to interpret the space in the way it normally does, which is as a separator between filenames or commands. Here’s how the command looks if you use backslashes:

stdin, stdout, and stderr

STDIN, STDOUT and STDERR are the three standard streams.

Standard input — this is the file descriptor that your process reads to get information from you.

Standard output — your process writes normal information to this file descriptor.

Standard error — your process writes errors or log messages to this file descriptor.

They are identified to the shell by a number rather than a name:

  • 0: stdin
  • 1: stdout
  • 2: stderr

By default, stdin is attached to the keyboard (Linux also allows you take standard input from a file using < ), and both stdout and stderr appear in the terminal.

So each of these numbers in your command refer to a file descriptor. You can either redirect a file descriptor to a file with > or redirect it to another file descriptor with >& .

>&number means redirect output to file descriptor number. So the & is needed to tell the shell you mean a file descriptor, not a file name.


echo will print whatever string it is given. You can redirect this string into a new file.

But if you want to add something else in the same file that already exists,

Using > command will erase everything what was inside. What if instead we want to append some line into already existing file? In this case we use >> .

You can use this command with every other commands.

This command redirects the stdout of ls -l to a file. If the file already existed, it is overwritten.

NOTE: > command is the same as 1> which implicitly means that “redirect all stdout to a file”. This 1 is just the file descriptor for stdout . The syntax for redirecting is [FILE_DESCRIPTOR]> , leaving the file descriptor out is just a shortcut to 1> . For example, the >&2 redirection is a shortcut for 1>& 2 .

because 1 stands for stdout .

So, to redirect stderr , it should be just a matter of adding the right file descriptor in place, which is 2> . Additionally, when you use 2>&1 you are basically saying “Redirect the stderr to the same place we are redirecting the stdout ”. For example:

Here, let’s add some text inside foo.txt .

Note that we don’t see any output in the screen after running cat foo.txt > output.txt 2>&1 because we use 2>&1 . However, let’s do the same for a file nop.txt that does not exist in the directory:

output.txt contains the error messages because we we are redirecting the standard error to output.txt too.

Note that >file 2>&1 is semantically equivalent to &> and >& .

>> is the same as > but if the file listing_home.txt already existed, stdout will be appended to the end of the file instead of overwriting it.

Let’s say we have two text files and we can concatenate them.

We can redirect this output to a new txt file.

When you run a sequence of commands in the interactive shell, like

then everything is executed consecutively and the output is send to the terminal.

Let’s say newfile.txt is a text file in our directory and has Hello! string in it. The command below

and this output will be written into file.txt .

The direction is not always from left to right. It can also be from right to left!

< takes the standard input from the file on the right instead of keyboard and inputs it into the program on the left.

A pipe is a form of redirection (transfer of standard output to some other destination) that is used in Linux and other Unix-like operating systems to send the output of one command/program/process to another command/program/process for further processing. The Unix/Linux systems allow stdout of a command to be connected to stdin of another command. You can make it do so by using the pipe character | . Its syntax is:

less is a command line utility that displays the contents of a file or a command output, one page at a time. It is similar to more , but has more advanced features and allows you to navigate both forward and backward through the file.

When starting less doesn’t read the entire file which results in much faster load times compared to text editors like vim or nano . The less command is mostly used for opening large files.

The general syntax for the less program is as follows:

You can also redirect the output from a command to less using a pipe.

will redirect the contents of the directory Desktop to command less .

find command is a command to look for some files you are interested in.

Let’s say the folder Desktop/newfolder/ has some files in it: aaa.txt and aaa_image.png :

will find files whose name starts with aaa .

will find all the folders in a folder.

will find all the files in a folder.

The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. Syntax:

Let’s create a new file.

Let’s add something inside of this text file.

Let’s search for so inside this file.

It will pick up the line son because grep is case-sensitive. The -i option enables to search for a string case insensitively in the give file.

It will also pick up every pattern wherever they are

You can pipe and use the grep command.

will grep the character t in the contents of the directory

You can also print out all the lines that do not matches the pattern using the option -v .

sudo command

The sudo command allows you to run programs with the security privileges of another user (by default, as the superuser). It prompts you for your personal password and confirms your request to execute a command by checking a file, called sudoers , which the system administrator configures. Using the sudoers file, system administrators can give certain users or groups access to some or all commands without those users having to know the root password. It also logs all commands and arguments so there is a record of who used it for what, and when.

To use the sudo command, at the command prompt, enter:

Replace command with the command for which you want to use sudo .

Let’s create a new file:

As you can see, newfile.txt will be owned by root . Everthing done by sudo command will be owned by root , superuser.

If we try to edit this file without using sudo command, we will get permission error!

We can also open whole new bash as root!

Changing the ownership

Let’s say we have a file dish.txt , whose ownership belongs to some other user or to root.

We can change its ownership.

As you can see now it belongs to the user mustafamuratarat .

We can also change the ownership to a different group.

Altering permissions of files

You can easily change permissions of files and directories by using the chmod command.

If you specify u , you can change permissions just for the owner ( u is for “user””, which is the same as “owner””). You can substitute a g to change group (guests) permissions. If you use a , it means all users including the owner, the group, and everybody else. Using an o , which is for “others””, will configure the file permissions for those who aren’t the owner of the file or who are not in the group that owns the file—the last three digits of the permission list.

In other words, you’re adding read and write (rw) permissions for all users (a), including the owner, the group, and everybody else. Here’s another example:

This tells Linux that you want to take away (-) the ability of all users (a) to write (w) to the file. However, you want to leave the other permissions as they are.

If you leave out the a , chmod assumes you mean “all”. In other words, commands like chmod a+r myfile and chmod +r myfile do the same thing.

This will add (+) read/write (rw) permissions for the owner.

This will configure the file so that members of the group that owns the file can’t read or write to it.

The access permission can be specified in the following format. The three parts of the format are given with no spaces between them.

General syntax is given by

  • Who can be any combination of:
    • u :user (the file’s owner).
    • g :group (the file’s group members).
    • o :others (everyone else).
      • :add the permissions to the file’s existing set.
      • :remove the given permissions from the file’s set.
      • r :read permission.
      • w :write permission.
      • x :execute permission for programs.


      Be careful with whitespaces. For a variable assignment, a contiguous string that contains = is important. The following will fail:

      In this case, bash splits the input myvar = 553 into three “words” ( myvar , = and 553 ) and then attempts to execute the first word as a command. This clearly is not what was intended here.

      We can unset the variable using command unset command:

      You can also use curly brackets to access to a variable:

      This can also be used for commands. Let’s say you invent a new command:

      Variable mycommand will act like command ls .

      There are already some variables saved in the system. These are called environment variables.

      If you run the printenv or env command without any arguments it will show a list of all environment variables:

      You can also use read command to read a variable.


      The alias command allows you to create keyboard shortcuts, or aliases, for commonly used commands. They are typically placed in the

      /.bash_profile in your text editor:

      and add your aliases:

      The aliases should be named in a way that is easy to remember. It is also recommended to add a comment for future reference.

      Once done, save and close the file. Make the aliases available in your current session by typing:

      source activates the changes in

      /.bash_profile for the current session. Instead of closing the terminal and needing to start a new session, source makes the changes available right away in the session we are in.

      Shell script

      The terminal usually allows just one command at the time. Shell scripts allow you to combine and run multiple commands together. A shell scripting is writing a program for the shell to execute and a shell script is a file or program that shell will execute. Shell scripts also allow you to use if-else statements and loops.

      Let’s create a new file called shortscript.txt .

      Let’s make it executable for all the users (we leave out the a , chmod assumes you mean “all”)

      In order to run this executable file, we can just do,

      Difference Between #!/bin/sh and #!/bin/bash

      As stated previously, bash and sh are two different shells. Basically bash is sh , with more features and better syntax. Most commands work the same, but they are different.

      bash binary is stored in the /bin/bash path in general. /bin/sh provides the sh shell which is cirppeled down version of the bash .

      We can use which command to see where our bash lives in:


      which command in Linux is a command which is used to locate the executable file associated with the given command by searching it in the path environment variable.

      info which : It displays help information.

      You can see this bin folder and locate all the built-in executable files:

      Even by clicking on these files, you can run those executables. So, when you run ls command on your command window, you are actually running /bin/ls .

      Creating the first script

      If you constantly run the same set of commands at the command line, why not automate that?

      Let’s create a file first!

      and then we add on the first line of the program,

      which is known as “Shebang”.

      Shebang contains path (of executable), from which you are telling Interpreter that execute following code from given executable path (followed by #! ).

      Since we are going to use Shell language, bash , the path is

      Let’s add some commands in this file!

      When we try to run it, we will get permission denied error.

      Because it is not executable! When we give necessary permissions and run it, it will work!

      However, .txt is not a proper extension for an executable file! For shell file, an appropriate extension is .sh . Let’s change it and run!

      Changing the path

      The information about where your programs are stored, and therefore where Ubuntu should look for commands you type in, as well as any programs you might want to run, is stored in the PATH variable. You can take a look at what’s currently stored there by typing the following:

      The echo command merely tells the shell to print something on screen. In this case, you are telling it to “echo”” the PATH variable onto your screen.

      Several directories are in this list, each separated by a colon.

      The important thing to know is that whenever you type a program name, the shell looks in each of the listed directories in sequence. In other words, when you type ls , the shell will look in each of the directories stored in the PATH variable, starting with the first in the list, to see if the ls program can be found. The first instance it finds is the one it will run.

      Let’s say you have a executable file myscript.sh inside a folder /Users/mustafamuratarat/Desktop/newfolder .

      Everytime you run it, it will ask you to enter your name!

      If you are already in the directory where the program in question is located, you can type the following:

      But what if you want to run a program that is not contained in a directory listed in your PATH ? In this case, you must tell the shell exactly where the program is.

      You have to enter the full path of the script with whichever directory you are in, i.e., /Users/mustafamuratarat/Desktop/newfolder/myscript.sh . If you do not do this, you will get “command not found” error!

      Let’s say you are on home directory and the script that you want to run is in another folder:

      Основы BASH. Часть 1

      break выход из цикла for, while или until
      continue выполнение следующей итерации цикла for, while или until
      echo вывод аргументов, разделенных пробелами, на стандартное устройство вывода
      exit выход из оболочки
      export отмечает аргументы как переменные для передачи в дочерние процессы в среде
      hash запоминает полные имена путей команд, указанных в качестве аргументов, чтобы не искать их при следующем обращении
      kill посылает сигнал завершения процессу
      pwd выводит текущий рабочий каталог
      read читает строку из ввода оболочки и использует ее для присвоения значений указанным переменным.\
      return заставляет функцию оболочки выйти с указанным значением
      shift перемещает позиционные параметры налево
      test вычисляет условное выражение
      times выводит имя пользователя и системное время, использованное оболочкой и ее потомками
      trap указывает команды, которые должны выполняться при получении оболочкой сигнала
      unset вызывает уничтожение переменных оболочки
      wait ждет выхода из дочернего процесса и сообщает выходное состояние.

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

      Что необходимо знать с самого начала

      1. Любой bash-скрипт должен начинаться со строки:

      в этой строке после #! указывается путь к bash-интерпретатору, поэтому если он у вас установлен в другом месте(где, вы можете узнать набрав whereis bash) поменяйте её на ваш путь.
      2. Коментарии начинаются с символа # (кроме первой строки).
      3. В bash переменные не имеют типа(о них речь пойдет ниже)

      Переменные и параметры скрипта

      Приведу как пример небольшой пример, который мы разберем:

      #указываем где у нас хранится bash-интерпретатор
      parametr1=$1 #присваиваем переменной parametr1 значение первого параметра скрипта
      script_name=$0 #присваиваем переменной script_name значение имени скрипта
      echo «Вы запустили скрипт с именем $script_name и параметром $parametr1» # команда echo выводит определенную строку, обращение к переменным осуществляется через $имя_переменной.
      echo ‘Вы запустили скрипт с именем $script_name и параметром $parametr1’ # здесь мы видим другие кавычки, разница в том, что в одинарных кавычках не происходит подстановки переменных.
      exit 0 #Выход с кодом 0 (удачное завершение работы скрипта)

      Результат выполнения скрипта:

      $ ./test.sh qwerty
      Вы запустили скрипт с именем ./test.sh и параметром qwerty
      Вы запустили скрипт с именем $script_name и параметром $parametr1

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

      $DIRSTACK — содержимое вершины стека каталогов
      $EDITOR — текстовый редактор по умолчанию
      $EUID — Эффективный UID. Если вы использовали программу su для выполнения команд от другого пользователя, то эта переменная содержит UID этого пользователя, в то время как.
      $UID — . содержит реальный идентификатор, который устанавливается только при логине.
      $FUNCNAME — имя текущей функции в скрипте.
      $GROUPS — массив групп к которым принадлежит текущий пользователь
      $HOME — домашний каталог пользователя
      $HOSTNAME — ваш hostname
      $HOSTTYPE — архитектура машины.
      $LC_CTYPE — внутренняя переменная, котороя определяет кодировку символов
      $OLDPWD — прежний рабочий каталог
      $OSTYPE — тип ОС
      $PATH — путь поиска программ
      $PPID — идентификатор родительского процесса
      $SECONDS — время работы скрипта(в сек.)
      $# — общее количество параметров переданных скрипту
      $* — все аргументы переданыне скрипту(выводятся в строку)
      $@ — тоже самое, что и предыдущий, но параметры выводятся в столбик
      $! — PID последнего запущенного в фоне процесса
      $$ — PID самого скрипта


      Условные операторы, думаю, знакомы практически каждому, кто хоть раз пытался на чем-то писать программы. В bash условия пишутся след. образом (как обычно на примере):
      source=$1 #в переменную source засовываем первый параметр скрипта
      dest=$2 #в переменную dest засовываем второй параметр скрипта

      if [[ «$source» -eq «$dest» ]] # в ковычках указываем имена переменных для сравнения. -eq — логическое сравнение обозначающие «равны»
      then # если они действительно равны, то
      echo «Применик $dest и источник $source один и тот же файл!» #выводим сообщение об ошибке, т.к. $source и $dest у нас равны
      exit 1 # выходим с ошибкой (1 — код ошибки)
      else # если же они не равны
      cp $source $dest # то выполняем команду cp: копируем источник в приемник
      echo «Удачное копирование!»
      fi #обозначаем окончание условия.

      Результат выполнения скрипта:

      $ ./primer2.sh 1 1
      Применик 1 и источник 1 один и тот же файл!

      $ ./primer2.sh 1 2
      Удачное копирование!

      Структура if-then-else используется следующим образом:
      if <команда или набор команд возвращающих код возврата(0 или 1)>
      <если выражение после if истино, то выполняется этот блок>
      <если выражение после if ложно, тот этот>
      В качестве команд возвращающих код возврата могут выступать структуры [[ , [ , test, (( )) или любая другая(или несколько) linux-команда.
      test — используется для логического сравнения. после выражения, неоьбходима закрывающая скобка «]»
      [ — синоним команды test
      [[ — расширенная версия «[» (начиная с версии 2.02)(как в примере), внутри которой могут быть использованы || (или), & (и). Долна иметь закрывающуб скобку «]]»
      (( )) — математическое сравнение.
      для построения многоярусных условий вида:
      if .
      then .
      if .
      else .

      для краткости и читаемости кода, можно использовать структуру:
      if ..
      then .
      elif .
      then .
      elif .

      Условия. Множественный выбор

      Если необходимо сравнивать какоую-то одну переменную с большим количеством параметров, то целесообразней использовать оператор case.
      echo «Выберите редатор для запуска:»
      echo «1 Запуск программы nano»
      echo «2 Запуск программы vi»
      echo «3 Запуск программы emacs»
      echo «4 Выход»
      read doing #здесь мы читаем в переменную $doing со стандартного ввода

      case $doing in
      /usr/bin/nano # если $doing содержит 1, то запустить nano
      /usr/bin/vi # если $doing содержит 2, то запустить vi
      /usr/bin/emacs # если $doing содержит 3, то запустить emacs
      exit 0
      *) #если введено с клавиатуры то, что в case не описывается, выполнять следующее:
      echo «Введено неправильное действие»

      esac #окончание оператора case.

      Результат работы:

      $ ./menu2.sh
      Выберите редатор для запуска:
      1 Запуск программы nano
      2 Запуск программы vi
      3 Запуск программы emacs
      4 Выход

      После выбор цифры и нажатия Enter запуститься тот редактор, который вы выбрали(если конечно все пути указаны правильно, и у вас установлены эти редакторы 🙂 )
      Прведу список логических операторв, которые используются для конструкции if-then-else-fi:
      -z # строка пуста
      -n # строка не пуста
      =, (==) # строки равны
      != # строки неравны
      -eq # равно
      -ne # неравно
      -lt,(< ) # меньше
      -le,(<=) # меньше или равно
      -gt,(>) #больше
      -ge,(>=) #больше или равно
      ! #отрицание логического выражения
      -a,(&&) #логическое «И»
      -o,(||) # логическое «ИЛИ»

      С основами языка и условиями мы разобрались, чтобы не перегружать статью, разобью её на несколько частей(допустим на 3). Во второй части разберем операторы цикла и выполнение математических операций.

      UPD: Исправил некоторые ошибки
      UPD: Обновил часть про условия if-then-else

      Основы работы с командной оболочкой bash в Linux

      Что такое Bash

      Командная оболочка Bash является одним из нескольких главных компонентов в дистрибутивах Linux. Она позволяет читать и запускать команды, выполнять скрипты, работать с файлами. Наличие Bash не менее важно для полноценного функционирования операционных систем семейства Linux, чем ядро или рабочее окружение.

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

      Что такое Bash

      Bash (Bourne again shell или «возрождённый» shell) – это модифицированная версия программной оболочки Bourne-shell (sh или «Оболочка Борна»). Она является командным процессором, работающим интерактивно в текстовом окне. Bash нужен для приема команд пользователя и их отправки операционной системе для последующей обработки.

      Что такое Bash

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

      История создания

      Предшественница Bash – Bourne-shell (sh, «Оболочка Борна») была одной из первых оболочек для операционных систем Unix. Ее создал в 1978 году британский ученый Стивен Борн, давший Bourne-shell свое имя.

      Изначально оболочка sh обладала относительно небольшим набором функций. Но в 1987 году Bourne-shell заинтересовался программист Брайан Фокс, сумевший доработать и значительно расширить ее функционал. В 1989 году Брайан создал бета-версию Bash и продолжал поддерживать свое детище вплоть до 1993 года.

      Брайан Фокс - создатель оболочки Bash

      Брайан Фокс — создатель оболочки Bash.

      Основные команды, правила их написания и прочие особенности Bash были перенесены из sh. Прочие возможности, включая историю, позаимствованы из Korn Shell и C Shell (других вариаций Bourne-shell). Bash практически полностью соответствует стандартам POSIX.

      Сегодня оболочка Bash предустановлена в большей части дистрибутивов Unix/Linux. Взаимодействие оболочки и операционной системы обеспечивается с помощью специальной программы – терминала (например, lxterm, xterm, eterm, gnome-terminal).


      Правила написания Bash представляют собой расширенный синтаксис Bourne-shell. Узнать подробности про основы взаимодействия с оболочкой, а также спецификации конкретных команд можно в руководстве Bash Reference Manual, распространяемом GNU. Это полезная шпаргалка для начинающих, позволяющая быстрее сориентироваться в оболочке.

      Пример скрипта

      Ниже рассмотрен пример самого простого скрипта, выводящего надпись «Hello world».

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

      Пример скрипта bash

      Отличие Bash от Bourne-shell

      Bash в Linux способна выполнять практически все важные сценарии Bourne-shell без внесения дополнительных изменений. Исключение составляют те, где необходимо ссылаться на спецпеременные Bourne-shell или, где применяются ее встроенные команды.

      В синтаксисе Bash применяются приемы из Korn Shell и C Shell:

      • редактирование командной строки;
      • вывод истории команд;
      • создание стеков директорий;
      • правила замены команд «$(…)»;
      • переменные «$PPID» и «$RANDOM».

      Используя консоль Bash в качестве интерактивного интерпретатора, можно прибегать к автодополнению названий файлов, программ, переменных и команд нажатием клавиши Tab (↹).

      Для чего нужен Bash

      Для чего нужен Bash

      Основные преимущества

      На данный момент разработано множество различных вариаций Bourne-Shell. Но, по сравнению с ними, командный интерпретатор Bash обладает рядом преимуществ.

      • Позволяет работать со структурами «[[» (в sh доступна только «[» с ограничениями).
      • Поддерживает работу с массивами в Линуксе.
      • Доступно множество расширений, выполненных по стандартам C, включая циклы с тремя аргументами «for((i=0;i<=3;i++))», возможность присваивать инкремент «+=» и многое другое.
      • Поддерживает синтаксис «<<<‘here strings’».
      • Работает с расширениями «.».
      • Доступны алиасы для перенаправления, подобно «Csh», подобно «&|» для «2>&1 |» и «&>» для «> … 2>&1».
      • Поддерживает сопроцессы с перенаправлением «<>».
      • Огромный комплект расширений нестандартных конфигураций, включая изменение регистра.
      • Существенно увеличены возможности арифметики (правда, нет поддержки чисел с плавающей точкой).
      • Переменные «$RANDOM», «$SECONDS», «$PIPESTATUS[@]» и «$FUNCNAME» в Bash являются расширениями.
      • Доступно огромное количества функций, обеспечивающих работу в интерактивном режиме. Хотя на поведение скриптов они не влияют.

      Примечание. Чем новее интерпретатор, тем больше функций он предоставляет. Узнать версию Bash в Linux можно командой:

      как узнать версию Bash в Linux

      Примеры применения

      • Вывести указанное количество строчек из лога.
      • Найти и составить выборку ключевых слов, сохранив их в новом файле.
      • Очистить экран терминала.
      • Приостановить работающие задачи и перезапустить ранее приостановленные.
      • Создать архив директории с файлами и отправить его на другой компьютер в одной сети через определенный сетевой протокол.
      • Произвести настройку системы создания резервных копий файлов баз данных, используя дампинг.
      • Послать запрос о конфигурации других компьютеров в сети. Отправить файл с собранной информацией на электронную почту.
      • Найти на диске дублированные файлы, отобразить их список и выполнить запрос их удалить.
      • Рекурсивно заменить владельцев указанных файлов и папок.

      Как работать с Bash

      Рассмотрим, как пользоваться Bash на примере подключения к веб-серверу (где находятся файлы сайта) с установленным дистрибутивом Linux через протокол SSH с нуля.

      Как работать с Bash

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

      1. После успешного ввода логина и пароля программа Терминал Linux в автоматическом режиме запустит Bash. Собственно, пользователь уже подключится к системе и увидит приглашение на ввод команд.

      2. Приглашение отображается относительно стандартно и имеет следующий вид:

      приглашение на ввод команд

      В примере:

      • размытием закрыто имя пользователя;
      • «vPro» – название компьютера;
      • графема тильда (

      3. Когда приглашение выполнено, терминал автоматически поставит пробел и будет находиться в ожидании ввода команд. На предложенном изображении была нажата кнопка «Enter». В следующей строчке введена команда «cd» перейти в существующий каталог «/opt». Еще ниже отображается результат вывода – рабочей папкой стала «/opt» и это показано в приглашении.

      результат вывода

      4. Командная строка Linux позволит запускать любое установленное в системе приложение. Как правило, каталоги со списком исполняемых программ расположены в папках «/bin, /usr/bin». Проверяемые каталоги интерпретатор сохраняет в переменной «$PATH». Просмотреть их список можно командой:

      5. Далее можно воспользоваться командой «ls» и добавить к ней один из каталогов, найденных в «$PATH», чтобы увидеть список доступных программ. Например:

       как увидеть список доступных программ

      6. Если приложение консольное, Bash произведет его запуск в терминале. Ниже показан пример запуска редактора Nano.

      запуска редактора Nano

      7. Bash также позволяет осуществлять запуск приложений в фоновом режиме. Для запуска в фоне, после ввода названия программы в конце следует добавить знак амперсанда (&).

      запуск Nano в фоне

      Здесь строка «[2] 23258» – это номер и PID процесса. При этом nano находится в фоновом режиме. Вернуться к нему можно командой «fg» (добавив номер задачи, если их запущено несколько) или «jobs».

      вернуть Nano в фоновый режим

      Поскольку в фоне может работать достаточно много команд, проверить номер требуемой можно командой «bg». Она отобразит список активных задач.

      отобразить список активных задач


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

      Оптимальное решение для размещения сайтов любого профиля и посещаемости — виртуальный сервер от Eternalhost. Оперативная техподдержка 24/7 и реально работающая бесплатная защита от DDoS.

      What is Bash (Unix Shell)?

      Website Developer

      Bourne Again Shell, most commonly known as Bash, is a command language and Unix shell. It runs in a text window and can run simple commands to do certain actions. It’s used to read and execute commands from a shell script. A file that can contain code from a variety of languages like Python or Java.


      Bash was created in 1989 by Brian Fox. Under the GNU project, Richard Stallman founded the Free Software Foundation who wished to create free software. The Free Software Foundation allowed the public access to many programs. Fox started working on Bash in 1988 after the previous programmer took too long on the project. Fox worked on the program until between 1992 and 1994 after being laid off and replaced by Chet Ramey.

      In 2017, Microsoft worked with Linux developers to add Bash to Windows. This allowed developers to be able to run Linux commands on Windows. Unfortunately on June 3, 2019, Apple decided to change its default shell from Bash to zsh. It is believed Apple did this due to the age and having to use an old version of bash.


      Bash has since become the default login shell for many Linux distributions. It was used on Macs until October 2019 after the Catalina update. There is also a port that lets Windows and Android users have access to Bash. These recent ports were created to bring the benefits of Linux to other platforms.

      Due to being the default shell on Linux, Bash continues to grow amongst consumers who are switching over to Linux. The chart below shows the market share of operating systems used by computers.

      The chart shows how in July 2019, 7.05% of all computers ran Linux. This allows Bash to be widely used amongst the Linux community and continue to grow. Also, the addition of Bash to Windows 10 allows a lot of consumers access to the language.


      Bash is widely available and can be accessed by many platforms. Bash is able to use command-line completion which allows the program to auto-complete what they’re typing. Developers used this to type variables, something that stores a value like a number, and file names. Bash is also used to search through the files in a computer and execute certain programs.

      Bash has many features and allows users to do many things. You can search through your computer to find files and folders, run a program, and work with many files. Bash is not only a language that is used by professionals but consumers as well.

      You can also use “?” to determine the success of a program. “?” is a built-in variable that is used often. Below is an example of the use of “?”.

      In the fourth line, the program is told to “echo $?” which means show us what the variable “?” is. We see that “?” equals zero which means the program, in general, was able to run without errors. If “?” equaled any number other than zero, this means there is an error that needs to be solved.

      Another thing to mention is that Bash is one of the highest paying languages amongst programmers. Below is a graph showing the median pay based on the language used.

      The graph shows Bash developers make about $100,000 a year. This may lead you to believe that the pay of these developers is high due to the demand for Bash developers. Yet, the high pay maybe because of the age of Bash developers. The graph below will show the age breakdown of programmers in many languages.

      This chart shows the age of Bash developers in comparison to other languages. Developers that work on Bash are more likely to be older and in turn, more experienced. In fact, of the 11,000 respondents, none were under the age of 29. This may mean because Bash developers are older, they have more experience in programming which leads to them having higher pay.


      Bash is rarely used to create a program but to pair with programs created in different languages. The time it takes to execute commands is also seen as slow in comparison to different languages. The code may be unreadable to other programmers and hard to understand. Errors are more common and cause developers to take extra care when developing.

      The age of the language also causes the code to seem hard to read causing a steep learning curve. This is in comparison to more modern languages that focus heavily on readability.

      It’s also recommended to not write long programs because that is not the primary function of the language. Quick commands or short programs is what most people use Bash for. If it is necessary to run a long program, you should use another language like Python or Java. Also, if performance is important for the program being created, you should use another language. Bash is slow compared to other languages meaning it should not be used as the main language.

      Examples of Code

      If Statement:

      If statements are used in programming to do something if something is true. The basic structure of an if statement is below.

      On the first line, we see what the condition is. Between the brackets, there must be a statement that is either true or false. This can be whether a number is greater than another or if a variable equals a number. Line three is where you write what you want the program to do like make it say something. Lastly, when it says “fi” that means that is the end of the if statement. Below is an example of an if statement that determines whether the person is of age to drink alcohol.

      $ #!/bin/bash
      $ # Basic if statement
      $ if [ $1 -gt 20 ]
      $ then
      $ echo That means you are old enough to drink.
      $ pwd
      $ fi

      We see in this example on line 4 the condition. It checks if the number from the first line, accessed from a file, is greater than 20. If the number is greater than 20 then we go to line 6 where it will say the quote. Once executed or if the condition is false the “fi” tells the computer the end of the if statement.

      A loop statement is used if you want to repeat a command or when something is true. There are two types of loops: a for loop and a while loop. Below is an example of a for loop.

      In the example, the first line is the start of the for loop. The “i” in the first line is a variable we are creating that will be used in this loop. The braces show the value “i” will be assigned to. The first number is the initial value of “i” at the beginning of the loop. The second number is the last value of “i” and stops the loop when “i” equals that number. Lastly, the last number is what number will add to “i” after each time through the loop. In the example “i” will start at 0, end at 10, and go up by 2. The third line shows the command the program will do which is say “Welcome $i times”. If “i” equals 2, it would say “Welcome 2 times”. The last line shows the end of the for loop by writing “done”.

      In the while loop, the first line shows assigning the letter “i” with a value of “0”. The third line is the start of the while loop. In the brackets, it means to do the command while “i” is less than 2. The fifth line is the command, and it tells the program to say “Number: $i”. If “i” equals 1 it would say “Number: 1”. The sixth line shows that to set the value of “i” up by one. Unlike the for loop, you need to increase the value of “i” by writing “((i++))”. The last line shows the end of the while loop allowing the program to continue.


      Bash is commonly used to deal with files stored in your computer. It can do many things involving files. Below is an example of creating a file.

      $ #!/bin/bash
      $ echo -n “Enter directory name ->”
      $ read dir
      $ if [ -d “$dir” ]
      $ then
      $ echo “Directory exists”
      $ else
      $ mkdir $dir`
      $ echo “Directory created”
      $ fi

      In the example, we see a program used to create a directory. On line 2, it asks the user the name of a directory and assign it to the variable “dir”. Then it checks if there is a directory with that name already. If there is it will say “Directory exists”. If the directory does not exist, then it will create a directory with that name. It does this by writing “mkdir” then the name of the directory. Finally, it will say “Directory created” and end the if statement. Below is an example of deleting a directory.

      $ #!/bin/bash
      $ echo -n “Enter filename ->”
      $ read name
      $ rm -i $name
      $ echo “File Deleted”

      In the example, we see a program used to delete a file. On line 2, it asks the user the name of the file to delete. It will store that in the variable named “name”. Then, by typing “rm -i” and the name it will delete the file. Finally, it will say “File Deleted” and end the program.


      The popularity of Bash grew as more and more consumers started using Linux. Many consumers had to learn how to use Bash to access their files, download programs, and more. The popularity also grew due to being the former default shell on macOS devices until being replaced in 2019.

      But Bash is not as often used amongst professionals in the community. We see below a chart showing the percentage of programming problems solved in Bash on codeeval.com.

      This chart shows in codeeval.com, a competitive programming website, only 0.4% of problems are solved with Bash. This means that Bash is one of the least used languages in the professional world. The popularity of the language with consumers continues to rise with the popularity of Linux.

      On September 12, 2014, Stéphane Chazelas told Chet Ramey of a bug in Bash. The bug allowed hackers to cause the computer to run commands. This bug was called “Shellshock” and was quickly updated on September 24. Once the update was sent out, an announcement was made of the bug report and what it could do. This led hackers to create programs to attack computers that had not yet updated Bash. The vulnerable devices from “Shellshock” was one of the highest due to a lot of computers with Bash.


      Bash is a widely used language on many devices. Due to being free software, it allowed many developers to have access to a shell. It is still widely used by Linux users and will continue to thrive in the technological future ahead. Although it may not be used highly amongst professionals, the consumer market will continue to grow.

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *