Press "Enter" to skip to content

10 Useful Chaining Operators in Linux with Practical Examples

We are thankful for your never ending support.

Linux əs-

Linux ƏS-nin yaranması 1991-ci ilə təsadüf edir. Finlandiyalı aspirant Linus Torvalds Minix ƏS-də proqram emulyasiyasını istifadə edərkən çox məyus oldu. Torvalds qərara gəldi ki, proqram emulyasiyasının kod hissəsini elə yazsın ki, ondan istifadə edərkən heç bir ƏS-ni çağırmağa ehtiyac qalmasın. Bir neçə modifikasoyadan sonra bu cür əməliyyat sistemi yaranmağa başladı. ƏS-nin proqram kodu serverdə yazıldı və bu proyekt proqramistlərin sayəsində mükəmməl ƏS oldu. Bu proyekt həmin vaxt artıq istifadə olunan Unix ƏS-nin əksər funksiyalarını özündə birləşdirdi. Proyektin adı mütəxəssislərin adlarının baş hərflərini və sonda X hərfi ilə adlandı. Linux ƏS birbaşa bu adla adlanmadı. Əvvəlcə o, Freax adlandı (mənası-pulsuz, sərbəst). Linus Torvalds serverdə kodu yazdıqdan sonra proyekt özünün son adını və loqotipini komputer texnikası sahəsində təsdiqlədi.

ƏS-nin tarixinə nəzər salanda Linux və Unix ƏS-lərinin üzərində iş 1969-cu ildə AT&T Bell Labs kompaniyasının işçisi Ken Tomison tərəfindən aparılmışdır. Belə ki, o, MULTİKS ƏS-ni yığcam şəkildə hazırlamalı idi ancaq nəticədə tam assembler dilində yazılmış və məzəli adı olan UNİCS (Uniplexed İnformation and Computing Service-sadə informasiya və hesablama xidməti) əs-mi meydana çıxdı. Sonralar isə sistemin rahat adlandırılması üçün Unix adından istifadə olundu.

Sonda proyektə Dennis Riççi və onun komandası cəlb olundu. Unix ƏS-mi yeni nəsil komputerlər üçün nəzərdə tutulmuşdu və ona görə də ƏS-nin kod hissəsi assembler dilindən yüksək səviyyəli C dilinə çevrildi. Həmin vaxt ƏS-ləri o qədər də sadə deyildi ona görə də Unix ƏS-mi tez bir zamanda universitetlərdən başlayaraq böyük çirkətlərə qədər hər yerdə istifadə olunmağa başladı. ƏS-mi ilə birlikdə onun proqram koduda istifadəçilərin ixtiyarına verildi. Belə ki, istifadəçi ƏS-nin kodunu dəyişə və ya ora yeni kodlar əlavə edə bilərdi. Bunun nəticəsində hər bir istifadəçi özü üçün xüsusi imkanlara malik Unix ƏS-mində işləyə bilərdi. Ona görə də Unix ƏS-nin bir çox versiyaları istifadəçilər arasında yayıldı və bu versiyalar original ƏS-dən çox-çox fərqlənirdi. Bunlardan məşhuru Berkli universitetinin hazırladığı Berkeley Unix versiyası oldu. Proqramistlər sistemə əlavə yeni imkanlar və proqramlar əlavə etdilər ki, bu da ƏS-nin komputer sahəsində geniş yayılmasına şərait yaratdı.

Unix ƏS-nin geniş yayılmış versiyalarına BSD, MİNİX (holland professoru Endro Tanenbauman tərəfindən hazırlanmışdı), SCO Unix, System V (AT&T çirkətinin original versiyası), Solaris (Sun şirkətinin məhsulu), XENİX və Linux-u misal göstərmək olar. Bunlardan ən geniş yayılmış ƏS-mi təbii ki, Linux-dur.

Linux-un rəsmi versiyası 1994-cü ildə istifadəçilərə təqdim olundu. ƏS-mi bütün lazımı funksiyaları o cümlədən şəbəkə ilə işləmək imkanını özündə birləşdirirdi. 1995-ci ildə isə Linux-un birinci məhsul nömrəsi qeydiyyatdan keçdi və 1996-cı ildə Linux 2.0 versiyası çıxdı. Linux-un birinci versiyasından indiyə kimi ƏS-mi GPL-in lisenziyası ilə (General Public License-standart ümumi lisenziya) sərbəst proqram təminatı ilə yayılıb. Hər bir istifadəçi ƏS-nin proqram koduna daxil olub, ora yeni kod əlavə edə bilər və ya istədiyi proqram kodunu dəyişə bilər. Hal-hazırda Linux ƏS-mi cib komputerlərində, mobil telefonlarda, fərdi komputerlərdə, serverlərdə, super komputerlərdə hətta musiqi alətlərində də istifadə olunur.

10 Useful Chaining Operators in Linux with Practical Examples

Chaining of Linux commands means, combining several commands and make them execute based upon the behaviour of operator used in between them. Chaining of commands in Linux, is something like you are writing short shell scripts at the shell itself, and executing them from the terminal directly. Chaining makes it possible to automate the process. Moreover, an unattended machine can function in a much systematic way with the help of chaining operators.

10 Chaining Operators in Linux

This Article aims at throwing light on frequently used command­-chaining operators, with short descriptions and corresponding examples which surely will increase your productivity and lets you write short and meaningful codes beside reducing system load, at times.

1. Ampersand Operator (&)

The function of ‘&‘ is to make the command run in background. Just type the command followed with a white space and ‘&‘. You can execute more than one command in the background, in a single go.

Run one command in the background:

[email protected]:~$ ping ­c5 www.tecmint.com &

Run two command in background, simultaneously:

[email protected]:/home/tecmint# apt-get update & apt-get upgrade &

2. semi-colon Operator (;)

The semi-colon operator makes it possible to run, several commands in a single go and the execution of command occurs sequentially.

[email protected]:/home/tecmint# apt-get update ; apt-get upgrade ; mkdir test

The above command combination will first execute update instruction, then upgrade instruction and finally will create a ‘test‘ directory under the current working directory.

3. AND Operator (&&)

The AND Operator (&&) would execute the second command only, if the execution of first command SUCCEEDS, i.e., the exit status of the first command is 0. This command is very useful in checking the execution status of last command.

For example, I want to visit website tecmint.com using links command, in terminal but before that I need to check if the host is live or not.

[email protected]:/home/tecmint# ping -c3 www.tecmint.com && links www.tecmint.com

4. OR Operator (||)

The OR Operator (||) is much like an ‘else‘ statement in programming. The above operator allow you to execute second command only if the execution of first command fails, i.e., the exit status of first command is ‘1‘.

For example, I want to execute ‘apt-get update‘ from non-root account and if the first command fails, then the second ‘links www.tecmint.com‘ command will execute.

[email protected]:~$ apt-get update || links tecmint.com

In the above command, since the user was not allowed to update system, it means that the exit status of first command is ‘1’ and hence the last command ‘links tecmint.com‘ gets executed.

What if the first command is executed successfully, with an exit status ‘0‘? Obviously! Second command won’t execute.

[email protected]:~$ mkdir test || links tecmint.com

Here, the user creates a folder ‘test‘ in his home directory, for which user is permitted. The command executed successfully giving an exit status ‘0‘ and hence the last part of the command is not executed.

5. NOT Operator (!)

The NOT Operator (!) is much like an ‘except‘ statement. This command will execute all except the condition provided. To understand this, create a directory ‘tecmint‘ in your home directory and ‘cd‘ to it.

[email protected]:~$ mkdir tecmint [email protected]:~$ cd tecmint

Next, create several types of files in the folder ‘tecmint‘.

[email protected]:~/tecmint$ touch a.doc b.doc a.pdf b.pdf a.xml b.xml a.html b.html

See we’ve created all the new files within the folder ‘tecmint‘.

[email protected]:~/tecmint$ ls a.doc a.html a.pdf a.xml b.doc b.html b.pdf b.xml

Now delete all the files except ‘html‘ file all at once, in a smart way.

[email protected]:~/tecmint$ rm -r !(*.html)

Just to verify, last execution. List all of the available files using ls command.

[email protected]:~/tecmint$ ls a.html b.html

6. AND – OR operator (&& – ||)

The above operator is actually a combination of ‘AND‘ and ‘OR‘ Operator. It is much like an ‘if-else‘ statement.

For example, let’s do ping to tecmint.com, if success echo ‘Verified‘ else echo ‘Host Down‘.

[email protected]:~/tecmint$ ping -c3 www.tecmint.com && echo "Verified" || echo "Host Down"
Sample Output
PING www.tecmint.com (212.71.234.61) 56(84) bytes of data. 64 bytes from www.tecmint.com (212.71.234.61): icmp_req=1 ttl=55 time=216 ms 64 bytes from www.tecmint.com (212.71.234.61): icmp_req=2 ttl=55 time=224 ms 64 bytes from www.tecmint.com (212.71.234.61): icmp_req=3 ttl=55 time=226 ms --- www.tecmint.com ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2001ms rtt min/avg/max/mdev = 216.960/222.789/226.423/4.199 ms Verified

Now, disconnect your internet connection, and try same command again.

[email protected]:~/tecmint$ ping -c3 www.tecmint.com && echo "verified" || echo "Host Down"
Sample Output
ping: unknown host www.tecmint.com Host Down

7. PIPE Operator (|)

This PIPE operator is very useful where the output of first command acts as an input to the second command. For example, pipeline the output of ‘ls -l‘ to ‘less‘ and see the output of the command.

[email protected]:~$ ls -l | less

8. Command Combination Operator <>

Combine two or more commands, the second command depends upon the execution of the first command.

For example, check if a directory ‘bin‘ is available or not, and output corresponding output.

[email protected]:~$ [ -d bin ] || < echo Directory does not exist, creating directory now.; mkdir bin; >&& echo Directory exists.

9. Precedence Operator ()

The Operator makes it possible to execute command in precedence order.

Command_x1 &&Command_x2 || Command_x3 && Command_x4.

In the above pseudo command, what if the Command_x1 fails? Neither of the Command_x2, Command_x3, Command_x4 would executed, for this we use Precedence Operator, as:

(Command_x1 &&Command_x2) || (Command_x3 && Command_x4)

In the above pseudo command, if Command_x1 fails, Command_x2 also fails but Still Command_x3 and Command_x4 executes depends upon exit status of Command_x3.

10. Concatenation Operator (\)

The Concatenation Operator (\) as the name specifies, is used to concatenate large commands over several lines in the shell. For example, The below command will open text file test(1).txt.

[email protected]:~/Downloads$ nano test\(1\).txt

That’s all for now. I am coming up with another interesting article very soon. Till then Stay tuned, healthy and connected to Tecmint. Don’t forget to give your Valuable feedback in our comment section.

Tutorial Feedback.

Was this article helpful? If you don’t find this article helpful or found some outdated info, issue or a typo, do post your valuable feedback or suggestions in the comments to help improve this article.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Ubuntu 23.04 «Lunar Lobster»: новый установщик, ядро Linux 6.2, GNOME 44

Обзор новых функций предстоящего релиза Ubuntu 23.04 «Lunar Lobster»: Новый установщик на Flutter, GNOME 44, улучшения в Nautilus, минимальный ISO-образ, Telegram в Snap, Ubuntu Cinnamon как новая официальная редакция, новые обои и ядро Linux 6.2

Первая бета версия дистрибутива Ubuntu 23.04 «Lunar Lobster» ожидается 30 марта 2023 года. Финальный релиз запланирован на 20 апреля.

Ubuntu 23.04 не является версией с долгосрочной поддержкой LTS, а значит будет поддерживаться в течение 9 месяцев до января 2024 года.

Ubuntu 23.04 «Lunar Lobster»: Что нового

Новый установщик

Новый установщик Ubuntu использует Flutter в своей основе. Теперь новый установщик доступен по умолчанию.

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

Вы можете ожидать, что на странице установщика будет добавлена отдельная опция «Восстановить», в том случае, если в вашей системе уже установлена Ubuntu 23.04.

Кроме того, переработанные установочные слайды будут лучше описывать преимущества/варианты использования операционной системы:

GNOME 44

Конечно, GNOME 44 — главная изюминка Ubuntu 23.04 .

Очевидно, что следует ожидать изменений оформления рабочего окружения поверх стандартного GNOME. Таким образом, внешний вид рабочего окружения GNOME 44 в Ubuntu будет отличаться от внешнего вида в дистрибутиве Fedora 38, где используется ванильный (стандартный) GNOME 44.

Например, значок инструмента для создания скриншотов в быстром меню здесь отличается, чтобы соответствовать теме оформления Ubuntu. Вы найдете несколько тонких различий, подобных этому.

В целом в GMONE 44 можно выделить следующие изменения:

  • Кнопка инструмента для создания скриншотов в быстром меню
  • Быстрый переключатель Bluetooth для просмотра/управления устройствами
  • Обновления файлового менеджера (например, улучшенная скорость поиска)
  • Мониторинг фоновых приложений

Новые функции файлового менеджера Nautilus

С обновлением GNOME 44 файловый менеджер Nautilus получил множество улучшений.

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

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

140-мегабайтный ISO-образ Ubuntu Mini

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

Новый ISO-образ можно использовать на небольших устройствах хранения, таких как CD/USB-накопители, или даже через UEFI HTTP.

Для последнего будет показано динамическое меню TUI (терминальный пользовательский интерфейс) образов Ubuntu, что позволит вам загрузить и установить образ по вашему выбору в целевой системе.

Приложение Telegram в формате пакетов Snap

Как и для установки веб-браузера Firefox, Ubuntu 23.04 может использовать переходный пакет для установки мессенджера Telegram в случае установки его из диспетчера пакетов (или терминала).

На момент публикации этой статьи мы не нашли ни одного переходного пакета deb-to-snap. Так что, возможно, Canonical могли удалить его из репозитория apt и ограничиться рекомендацией по установке формата Snap для Telegram.

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

Ubuntu Cinnamon в качестве новой официальной редакции

С релизом Ubuntu 23.04 Ubuntu Cinnamon Remix больше не будет являться неофициальной редакцией.

В семействе редакций Ubuntu появится новая официальная редакция – Ubuntu Cinnamon.

Новые обои рабочего стола

Доступна новая коллекция обоев от дизайнеров сообщества, победивших в конкурсе обоев для рабочего стола.

Стоковые обои рабочего стола для Ubuntu 23.04 доступны по ссылке.

Ядро Linux 6.2

Хотя Ubuntu 23.04 не является LTS-версией, новая версия дистрибутива будет поставляться с ядром Linux 6.2.

На данный момент ежедневная сборка поставляется с ядром Linux 6.1, но компания Canonical подтвердила, что Ubuntu 23.04 будет использовать ядро Linux 6.2.

Другие изменения

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

Некоторые из заслуживающих внимания изменений включают в себя:

  • Поддержка категорий при поиске приложений в Центре приложений
  • Средство обновления прошивки добавлено как отдельное приложение в Snap Store.
  • PostgreSQL 15
  • Qemu v7.2.0 с поддержкой Risc-V
  • Rclone 1.60.1
  • Ruby 3.1
  • NetworkManager 1.42

Как скачать ISO образ Ubuntu 23.04 «Lunar Lobster»

Скачать ISO-образ Ubuntu 23.04 (Lunar Lobster) Daily Build можно по ссылке с помощью нашего сайта.

Итак, что вы думаете о новой версии Ubuntu 23.04?

Comments are closed, but trackbacks and pingbacks are open.