Linux bash array in array

Содержание
  1. Работа с массивами в bash
  2. Реальная задача, в которой пригодятся bash-массивы
  3. Основы
  4. Способы обращения к элементам массивов
  5. Перебор элементов массивов в циклах
  6. Перебор индексов массивов в циклах
  7. Заполнение массивов
  8. Полезные синтаксические конструкции
  9. Решение задачи
  10. Что дальше?
  11. Оповещения о проблемах
  12. Запросы к API
  13. Bash или Python?
  14. Итоги
  15. Массивы bash
  16. Full Guide to Bash Arrays
  17. 1 Bash Scripting:
  18. 2 What Are Arrays?
  19. 3 Applications of Arrays:
  20. 4 Syntax of Arrays in Bash:
  21. 5 Assigning Arrays in Bash:
  22. 5.1 Assigning Arrays Through Loop:
  23. 5.2 Assigning Arrays From Strings:
  24. 6 Types of Array in Bash:
  25. 6.1 Indexed Arrays:
  26. 6.2 Associative Arrays:
  27. 7 Accessing an Array in Bash:
  28. 7.1 Displaying All Elements of an Array:
  29. 7.2 Displaying Specific Element of an Array:
  30. 7.3 Accessing the Initialized Indexes of Array:
  31. 8 Modification of Arrays in Bash:
  32. 8.1 Updating Elements:
  33. 8.2 Adding Elements:
  34. 8.3 Inserting Elements:
  35. 8.4 Deleting Elements:
  36. 8.5 Merging Arrays:
  37. 8.6 Removing Gaps in Array Elements:
  38. 9 Iterating Through the Array with Loops in Bash:
  39. 10 Length of an Array in Bash:
  40. 11 Accessing Associative Arrays in Bash:
  41. 12 Bash Array Examples:
  42. 12.1 Example 1: Reading a File Through Array:
  43. 12.2 Example 2: Bubble Sorting in Bash:
  44. 12.3 Example 3: Multidimensional Arrays in Bash:
  45. 12.4 Example 4: Formatting a Poem in Bash:
  46. Conclusion:
  47. About the author
  48. Sam U

Работа с массивами в bash

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

Реальная задача, в которой пригодятся bash-массивы

Писать о bash — занятие неоднозначное. Дело в том, что статьи о bash нередко превращаются в руководства пользователя, которые посвящены рассказам о синтаксических особенностях рассматриваемых команд. Эта статья написана иначе, надеемся, вам она не покажется очередным «руководством пользователя».

Учитывая вышесказанное, представим себе реальный сценарий использования массивов в bash. Предположим, перед вами стоит задача оценить и оптимизировать утилиту из нового внутреннего набора инструментов, используемого в вашей компании. На первом шаге этого исследования вам нужно испытать её с разными наборами параметров. Испытание направлено на изучение того, как новый набор инструментов ведёт себя при использовании им разного количества потоков. Для простоты изложения будем считать, что «набор инструментов» — это скомпилированный из C++-кода «чёрный ящик». При его использовании единственным параметром, на который мы можем влиять, является число потоков, зарезервированных для обработки данных. Вызов исследуемой системы из командной строки выглядит так:

Основы

В первую очередь объявим массив, содержащий значения параметра —threads , с которыми мы хотим протестировать систему. Выглядит этот массив так:

В этом примере все элементы являются числами, но, на самом деле, в bash-массивах можно хранить одновременно и числа, и строки. Например, вполне допустимо объявление такого массива:

Как и в случае с другими переменными bash, обратите внимание на то, чтобы вокруг знака = не было бы пробелов. В противном случае bash сочтёт имя переменной именем программы, которую ему нужно выполнить, а = — её первым аргументом!

Теперь, когда мы инициализировали массив, давайте извлечём из него несколько элементов. Тут можно заметить, например, что команда echo $allThreads выведет лишь первый элемент массива.

Для того чтобы понять причины такого поведения, немного отвлечёмся от массивов и вспомним, как работать с переменными в bash. Рассмотрим следующий пример:

Предположим, что имеется переменная $type , которая содержит строку, представляющую собой имя существительное. После этого слова надо добавить букву s . Однако нельзя просто добавить эту букву в конец имени переменной, так как это превратит команду обращения к переменной в $types , то есть, работать мы уже будем с совершенно другой переменной. В данной ситуации можно воспользоваться конструкцией вида echo «Found 42 «$type»s» . Но лучше всего решить эту задачу с использованием фигурных скобок: echo «Found 42 $s» , что позволит нам сообщить bash о том, где начинается и заканчивается имя переменной (что интересно, тот же синтаксис используется в JavaScript ES6 для внедрения переменных в выражения в шаблонных строках).

Теперь вернёмся к массивам. Оказывается, что, хотя фигурные скобки при работе с переменными обычно не нужны, они нужны для работы с массивами. Они позволяют задавать индексы для доступа к элементам массива. Например, команда вида echo $ выведет второй элемент массива. Если в вышеописанной конструкции забыть о фигурных скобках, bash будет воспринимать [1] как строку и соответствующим образом обработает то, что получится.

Как видите, массивы в bash имеют странный синтаксис, но в них, по крайней мере, нумерация элементов начинается с нуля. Это роднит их с массивами из многих других языков программирования.

Способы обращения к элементам массивов

В вышеописанном примере мы использовали в массивах целочисленные индексы, задаваемые в явном виде. Теперь рассмотрим ещё два способа работы с массивами.

Первый способ применим в том случае, если нам нужен $i -й элемент массива, где $i — это переменная, содержащая индекс нужного элемента массива. Извлечь этот элемент из массива можно с помощью конструкции вида echo $ .

Второй способ позволяет вывести все элементы массива. Он заключается в замене числового индекса символом @ (его можно воспринимать как команду, указывающую на все элементы массива). Выглядит это так: echo $ .

Перебор элементов массивов в циклах

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

Перебор индексов массивов в циклах

Рассмотрим теперь несколько иной подход к перебору массивов. Вместо того, чтобы перебирать элементы, мы можем перебирать индексы массива:

Разберём то, что здесь происходит. Как мы уже видели, конструкция вида $ представляет собой все элементы массива. При добавлении сюда восклицательного знака мы превращаем эту конструкцию в $ , что приводит к тому, что она возвращает индексы массива (от 0 до 7 в нашем случае).

Другими словами, цикл for перебирает все индексы массива, представленные в виде переменной $i , а в теле цикла обращение к элементам массива, которые служат значениями параметра —thread , выполняется с помощью конструкции $ .

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

Заполнение массивов

До сих пор мы исследовали систему, вызывая команду pipeline с передачей ей каждого интересующего нас значения параметра —threads . Теперь предположим, что эта команда выдаёт длительность выполнения некоего процесса в секундах. Нам хотелось бы перехватить возвращаемые ей на каждой итерации данные и сохранить в другом массиве. Это даст нам возможность работать с сохранёнными данными после того, как все испытания закончатся.

Полезные синтаксические конструкции

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

После выполнения этой команды то, что выведет скрипт myscript.sh , будет сохранено в переменной $output .

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

Решение задачи

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

Что дальше?

Только что мы рассмотрели способ использования bash-массивов для перебора параметров, используемых при запуске некоей программы и для сохранения данных, которые возвращает эта программа. Однако этим сценарием варианты использования массивов не ограничиваются. Вот ещё пара примеров.

Оповещения о проблемах

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

Запросы к API

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

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

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

Bash или Python?

Массивы — возможность полезная и доступна она не только в bash. У того, кто пишет скрипты для командной строки, может возникнуть закономерный вопрос о том, в каких ситуациях стоит использовать bash, а в каких, например, Python.

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

Читайте также:  Советы для повышения производительности компьютера windows 10

Например, для решения рассмотренной здесь задачи можно воспользоваться и скриптом, написанным на Python, однако, это сведётся к написанию на Python обёртки для bash:

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

Итоги

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

Синтаксическая конструкция Описание
arr=() Создание пустого массива
arr=(1 2 3) Инициализация массива
$ Получение третьего элемента массива
$ Получение всех элементов массива
$ Получение индексов массива
$ Вычисление размера массива
arr[0]=3 Перезапись первого элемента массива
arr+=(4) Присоединение к массиву значения
str=$(ls) Сохранение вывода команды ls в виде строки
arr=( $(ls) ) Сохранение вывода команды ls в виде массива имён файлов
$ Получение элементов массива начиная с элемента с индексом s до элемента с индексом s+(n-1)

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

Уважаемые читатели! Если у вас есть интересные примеры применения массивов в bash-скриптах — просим ими поделиться.

Источник

Массивы bash

Предлагаю вашему вниманию перевод статьи Митча Фрейзера (Mitch Frazier) «Bash Arrays» с сайта linuxjournal.com.

Если вы используете «стандартную» оболочку *NIX-системы, возможно, вы не знакомы с такой полезной особенностью bash как массивы. Хотя массивы в bash не так круты, как в P-языках (Perl, Python и PHP) и других языках программирования, они часто бывают полезны.
Bash-массивы имеют только численные индексы, но они не обязательны к использованию, то есть вы не должны определять значения всех индексов в явном виде. Массив целиком может быть определен путем заключения записей в круглые скобки:

Отдельные записи могут быть определены с помощью знакомого всем синтаксиса (от Бейсика (да простит меня Дейкстра — прим. переводчика) до Фортрана):

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

Из страницы man:

«Фигурные скобки нужны для предотвращения конфликтов при разворачивании полных путей к файлам.«

Кроме того, доступны следующие странноватые конструкции:

$ — сравнительно новое дополнение в bash и не является частью оригинальной реализации. Следующая конструкция демонстрирует пример простого использования массива. Обратите внимание на «[index]=value», это позволяет назначить конкретное значение конкретному номеру записи.

Запуск скрипта породит следующий вывод:

one
two
three
four
five

Array items and indexes:

0: one
1: two
2: three
3: four
5: five

Обратите внимание, что символ «@» может быть использован вместо «*» в конструкциях типа , результат будет одинаковым за исключением разворачивания записи в кавычках. «$*» и «$@» выведут записи в кавычках, «$» вернет каждую запись как одно слово, «$» вернет каждую запись в виде отдельных слов.

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

Вывод при запуске:

Number of items in original array: 4

first item
second item
third
item

After unquoted expansion: 6

first
item
second
item
third
item

After * quoted expansion: 1

first item second item third item

After @ quoted expansion: 4

first item
second item
third
item

Источник

Full Guide to Bash Arrays

Linux shell is a program with an interface that takes commands from the user, interprets them, and sends them to the kernel to perform a specified operation. Command Line Interface (CLI) is the minimalist way to interact with the hardware of the system. There are tons of commands for performing various functionalities, such as making a directory, moving a directory, creating a file, deleting a file, etc.

Shell is a basic command-line interpreter. It yields an interface between the user and the kernel. In Linux, there are many types of shells; a list of commonly used shells are mentioned below:

  • Bourne Shell
  • Bourne Again Shell [Bash]
  • C Shell
  • Korn Shell
  • TC Shell

Different types of shells offer different capabilities. Ken Thompson introduced the first shell for Unix called Thompson Shell. Bourne shell was one of the widely adopted shells developed by Stephen Bourne in 1977 at Bell Laboratories. Bourne Shell has an advanced version called Bourne Again Shell. Bourne Again Shell is also called Bash. Bash was developed by Brian Fox that contained all the features of the Bourne shell but was it much more efficient.

Bash is the default shell from many Linux distributions, and the key features that distinguish Bash from share are mentioned below:

  • The powerful command editing feature
  • Unlimited size of event history
  • Introduction of aliases
  • Unlimited size of arrays

Bash shell has many advanced features, including powerful editing and modification features, making it incredibly user-friendly.

The commands are the fundamental part of Bash; commands tell the shell what operation to perform. In general, the shell takes one command at a time, runs it, and then displays the output, which is also called standard output in the shell. While executing a command, you cannot interact with the shell; the shell completes the operation before making itself available for the next command. However, the execution of any command can be interrupted. The time of execution of command ultimately depends upon the type of function. For instance, if you are downloading a package, it might take longer than listing the current working directory path.

Though the shell is designed to execute one command at a time, if you want to execute multiple commands to perform a specific task, Bash has a solution called Bash scripting.

1 Bash Scripting:

A script is a set of commands that tells the computer what it should do; a Bash script is also a set of commands that tells what Bash should perform. A Shell script is a text file that contains a sequence of commands to perform a particular task. Bash used Bash programming language, which like any other programming language, provides all the tools to perform logical operations such as assigning variables, conditional statements, loop structures, and arrays.

As mentioned above, Bash scripting is like any other programming language. To create a Bash program, you do not need a powerful Integrated Development Environment (IDE) because it can be made on any simple text editor, whether it is nano, vim, or text editor that comes with the desktop environment.

To create a Bash script, open the text editor and reference the “/bin/bash” path using “#!” called hash-bang or shebang. The “/bin/bash” is the path of the Bash interpreter. The formatting in Bash scripting is very crucial; even a space can cause errors. And shebang has to be on the top of the script. Type the script and save the file with the “.sh” extension. A basic “hello world” Bash script is shown below:

echo “Hello Linux”

To run the script in the CLI, type “bash” and specify the path of the script.

Assigning variables in Bash scripting is simple. It does not need any data type; any character, word, or string can be used as a variable:

var =”Hello Linux”

The “Hello Linux” string is assigned to a variable called “var” in the above script. As a proper programming language, Bash also supports conditional structures such as if-then, nested-if, and loop structures such as for-in and while-do.

A single variable can hold one value that can be manipulated in the code. If you want to define more than one variable of the same data type simultaneously, arrays are used. Moreover, arrays are also key elements of the Bash programming language. Arrays are a collection of elements that are identified by the index number. Arrays are essential when it comes to implementing data structure. Instead of typing multiple variables, arrays save time and are easy on memory.

2 What Are Arrays?

The developers use many aspects of the Bash programming language. There is plenty of data available for other programming structures such as loops and conditional statements, but a structure that is not extensively covered is an array. The Bash array is a crucial structure of any programming language. It is implemented in the data structure.

Let’s understand array with a real-life example:

  • Post office box
  • Pages of a book
  • Chessboard
  • A carton of eggs

The array is an arrangement of items. Therefore, every item is called an array if arranged in a manner. For example, egg cartons are the perfect example of the arrangement of items in 2D array manner. Eggs in the carton are elements where the box is an array. Similarly, pages in a book are arranged so the book would be called an array where pages would be elements.

Likewise, the contact numbers in our phones, songs, and an arrangement of apps on the home screen are also examples of an array.

Let’s take an example of contacts in our phone, and the contact book is an example of an array where the contacts are elements of that array. We can manipulate the elements, such as adding a contact number and deleting a contact number.

In the above demonstration, the contact numbers are elements of the array where the numbers above are memory locations.

When you visit an eCommerce site, the items you put in the shopping cart are also an example of an array, since you can add items to the shopping cart and remove them.

A variable that can store multiple variables is called an array. There is no limit when it comes to assigning a number of variables in an array. Array elements are referenced by the index number, which usually starts with zero. The array is mainly used in implementing data structure, which is an approach to organize and manage data effectively. Let’s visualize an array as a container with multiple compartments, as shown in the image below:

There are ten compartments in the above demonstration, so the length of the array would be 10. The first compartment number would be 0 and the last would be 9. The compartments can also be termed as the elements of the array.

Instead of defining multiple variables one by one, arrays help them define them at once; that is an efficient way of assigning variables in programming.

3 Applications of Arrays:

Arrays are such a powerful utility that they can be used in many scientific calculations. Arrays in any programming language are much more functional than other structures. Some notable implementation of arrays are mentioned below:

  • Arrays are used to manage multiple variables with the same name.
  • Arrays can be used in vectors, where vectors are typically one-dimensional arrays that are extensively used in machine learning.
  • Arrays are also used in implementing stacks, and stacks behave like a real pile of physical objects.
  • Arrays are also implemented in queues, deques, and hash tables.
  • Matrices, which are a rectangular array of elements, are also implemented using arrays.
  • Graphs in many programs are drawn using lists which is also any implementation of array.
  • Many algorithms, such as CPU scheduling algorithms and sorting algorithms, are implemented using the array.
  • Arrays are also used in in-program dynamic memory allocation.
  • Arrays are also used in speech processing.
  • Noise removing filters are also using arrays.

The above implementations of arrays clearly show the potential of the arrays data type.

4 Syntax of Arrays in Bash:

Bash comes with the support of both indexed array (one-dimensional array) and associative arrays, which will be discussed in the later section. A typical syntax of assigning array in Bash is mentioned below:

Since arrays are collections of objects, the object number in the array is called index number or subscript. Subscripts indicate the position of the object in the array. For instance, to assign or modify the value of x th object in the array, the syntax would be:

The “declare” keyword can also be used to declare an array:

To declare an associative array:

The syntax of compound assignment of an array is:

Any of the previously mentioned methods can be utilized to state arrays in Bash scripting.

5 Assigning Arrays in Bash:

Arrays in Bash scripting can be assigned in various ways. The simplest way to assign an array in Bash scripting is assigning a set of values with space in round brackets to a variable as demonstrated below:

The Bash arrays can have different types of elements. To assign array with string elements:

To explicitly assigning an array with indices:

To assign the array with index, type the name of the array, mention the index in the square brackets, “[index_number]” and assign a value to it:

my_array [ 0 ] =’jan’

my_array [ 1 ] =’feb’

The array can also be declared with the “declare” keyword. The options “-a” and “-A” is used to declare indexed and associative arrays, respectively:

declare -a my_array

my_array [ 0 ] =’jan’

my_array [ 1 ] =’feb’

String values are used as the index in associative arrays:

declare -A my_array

my_array [ first ] =’jan’

my_array [ second ] =’feb’

The array can also be created from the output of other commands.

For example, the “seq” command is used to create a list of numbers:

5.1 Assigning Arrays Through Loop:

Array can also be assigned through loops, for example:

my_array [ $n ] = $REPLY

echo “Array elements are:” $

The “$REPLY” is the special variable and equals the current input.

5.2 Assigning Arrays From Strings:

An entire string can also be assigned as an array. For example:

my_array_string =”Hello this is Linux”

In the above script, the delimiter is a “space”. A delimiter is a character that individualizes the text string, such as slashes, commas, colons, pipes, and even spaces. In the next example, the delimiter is dash:

Let’s implement it in Bash scripting:

my_array_string = «Hello this is Linux»

6 Types of Array in Bash:

There are many ways and approaches to use an array. In Bash, there are two types of primary arrays:

  • Indexed arrays
  • Associative arrays

6.1 Indexed Arrays:

Indexed arrays are the primary form of an array that stores elements referenced through an index number starting from 0. An example of an indexed array in Bash scripting is mentioned below:

Or arrays can also be declared using the “declare” keyword:

my_array [ 0 ] = “First Item”

my_array [ 1 ] = “Second Item”

In the above example, “array” is a variable “a, b, c, and d” are the elements of the array. The array’s length would be 4, and the index number of the “a” element would be on the zeroth index and “d” on the third index.

6.2 Associative Arrays:

Associative arrays are the arrays that use string as index. In other words, the array index in associative arrays is in named form. Associative arrays are declared in Bash using the “declare” keyword.

declare -A my_array

my_array [ one ] = “First Item”

my_array [ two ] = “Second Item”

Associative arrays are not part of Bash before they are included in version 4. To identify which version are you using, use the command given below:

If the version is four or above, then you can use associative arrays. To declare associative array “-A” option is used explicitly:

Elements can also be initialized one by one:

my_array [ month1 ] =”jan”

my_array [ month2 ] =”feb”

Any string or set of characters are used to declare an associative array:

It is important to note that the string in the array indexes, as mentioned above, is containing space. Another way of initialization of associative arrays are given below:

Currently, Bash does not support multidimensional arrays. However, different methods can emulate multidimensional arrays, which can be found in the examples section.

7 Accessing an Array in Bash:

Like all other programming languages, arrays in Bash are also accessed through index numbers. Let’s understand it through an example:

my_array = ( jan feb mar apr )

The “echo” is a Bash command that prints the standard output in the command-line interface (CLI). In the above example, the “echo” command is printing the item on the first index of the array “my_array”. The “feb” will be printed on the standard output since the index number of “feb” is 1.

7.1 Displaying All Elements of an Array:

To display all the elements of the array quoted separately, follow:

To display all the elements as a single quote string, use:

7.2 Displaying Specific Element of an Array:

To display any element of the array, use:

Replace the “x” with the index number of the element you want to display. For example, to print the third element of the array, use:

Print last element of an array through the subscript expansion method:

To print the last element via subscript syntax, use:

To print a range of elements, use the syntax mentioned below:

Where “x” is the first index number, and the “y” would be the last index number. For instance, to display elements from index “0” to “2”, use:

The above command will print three elements from index 0 to 2. All the operations for accessing arrays are demonstrated in the following image:

my_array = ( jan feb mar apr )

echo «All the elements of the array:» $

echo «The second element of the array:» $ #index starts from 0

echo «Last element of the array through substring expansion:» $

echo «Last element of the array through subscript:» $

echo «Elements from index 1 to 3:» $

7.3 Accessing the Initialized Indexes of Array:

The index of an array is the key element while programming. To get the index number, use:

my_array [ 3 ] =”jan”

my_array [ 5 ] =”feb”

my_array [ 9 ] =”mar”

my_array [ 12 ] =”mar”

echo “The list of indexes:” $

8 Modification of Arrays in Bash:

One of the benefits of using arrays is that any array element can easily be accessed and modified. Arrays in Bash have various ways to change; all the methods are mentioned below:

8.1 Updating Elements:

To update a particular element in an array, follow the following syntax:

my_array = ( jan feb mar apr )

my_array [ 2 ] =”may”

echo “The updated element:” $

In the above example, the element on the second index, which is “mar” will be replaced by “may”.

8.2 Adding Elements:

To add elements to the end of an array:

To add an element at the starting of an array:

Let’s implement it in a Bash script:

my_array = ( jan feb mar apr )

my_array+= ( jun jul )

echo «Array after adding elements:» $

echo «Adding element at the end of the array:» $

8.3 Inserting Elements:

To insert an element at a specific index, follow:

my_array ( jan feb mar apr )

The above example is inserting the element “aug” on the second index of the array(my_array) and shifting the following elements to the next indexes. The elements “mar” and “apr” will be shifted to index 3 and 4 respectively:

my_array = ( jan feb mar apr )

echo «Array after inserting an element:» $

8.4 Deleting Elements:

In Bash arrays, elements can be deleted using the “unset” command. For example, to remove all the elements of an array, use:

my_array = ( jan feb mar apr )

The “unset” is the built-in command to delete the declared variables. To unset a specific element in an array, use:

my_array = ( jan feb mar apr )

unset my_array [ 2 ]

echo “Array after deletion of element on third index:” $

Elements can also be removed using the “pattern” command:

The elements that start with “ju” will be removed from the array, as shown in the output of the following script:

my_array = ( jan feb mar apr may jun jul )

echo “Array after elements deletion by pattern:” $

8.5 Merging Arrays:

To merge two arrays use:

Let’s merge two arrays in Bash:

my_array1 = ( jan feb mar apr )

my_array2 = ( may jun jul aug )

echo «The merged array:» $

8.6 Removing Gaps in Array Elements:

To remove the unintended gaps in the array and re-indexing array use:

my_array = ( jan feb mar apr )

echo “Array after removing gaps:” $

In the above demonstration, elements of “my_array” have gaps in them.

9 Iterating Through the Array with Loops in Bash:

There are various ways to access an array; either you can access them explicitly by typing every element, or you can loop through the elements of the array. Let’s understand it through an example:

First, use the “for…in” loop:

C is a widely used programming language. Luckily in Bash, you can also use the C language style “for” loop, which is also termed as the classic loop:

Arrays can also be accessed through while loop:

echo my_array [ $i ]

Instead of “-lt”, the less than sign “ i = 0

echo my_array [ $i ]

The until loop can also be used to iterate through the arrays:

In numerical format:

The script of implementation of all the loop structures in Bash is mentioned below:

10 Length of an Array in Bash:

Knowing the length of the array is very important when working with arrays. To identify the length of an array, use:

my_array = ( jan feb mar apr )

The character “#” is used before the array name.

If the elements of an array are in a string format, then to know the length of a string element in an array, use:

my_array = ( january february march april )

The above commands will output the length of the second element of the array, which is 8, since “february” is 8 characters long.

my_array = ( jan feb mar apr )

echo «The length of the array:» $

my_array = ( january february march april )

echo «The length of the string element:» $

11 Accessing Associative Arrays in Bash:

Accessing the associative arrays are similar to accessing the indexed arrays. The only difference is that in associative arrays the index is string:

declare -A my_array = ( [ month1 ] =jan [ month2 ] =feb [ month3 ] =mar )

To list the indices of associative arrays, use:

To display the values of the array, use:

Iterate through the associative arrays:

my_array = ( [ month1 ] =jan [ month2 ] =feb [ month3 ] =mar [ month5 ] =apr )

echo my_array [ $i ]

To count the elements of the associative arrays, use:

my_array = ( [ month1 ] =jan [ month2 ] =feb [ month3 ] =mar [ month5 ] =apr )

All the previously mentioned structures are implemented in the script given below:

#! /bin/bash
declare -A my_array = ( [ month1 ] = «jan» [ month2 ] = «feb» [ month3 ] = «mar» [ month4 ] = «apr» )
echo «The first element:» $
echo «Indexes of associative arrays:» $
echo «Number of elements of associative array:» $ <#my_array[@]>
echo «Elements of associative arrays:» $
#————-Iterating the associative array——————-

Action
echo $array[@] To print all elements of an array
echo $!array[@] To print the all indexes of an array
echo $#array[@] To print the length of an array
echo $array[x] To print a specific element of an array by index “x”
array[x]=value To insert/replace an element to a specific index of an array
unset array[x] To remove an element at a specific index

12 Bash Array Examples:

Bash arrays are the data structure and are very useful for handling the collection of variables. Arrays have various uses in programming. Let’s further elaborate on the uses of arrays through examples:

12.1 Example 1: Reading a File Through Array:

To read a file, we need to create a file first. There are various ways to create a file in Linux, for instance, using a redirection operator, cat, or touch command. The created file can be edited in nano or vim editor.

I have created a file in “nano” and saved it with the name of “my_file.txt”. To read file, use:

echo “Enter the name of the file ”

file = ( ` cat “ $file ” ` )

12.2 Example 2: Bubble Sorting in Bash:

Sorting is used to manage the data, and it is one of the well-known techniques in programming to make the algorithm functionality more efficient such as search algorithm. Bubble sorting, which is also known as sinking sorting, is one of the easy-to-understand sorting approaches. Bubble sort steps through the provided array list, compare the array elements, swap the element in the temporary variables and repeat the task until the array is in order. An example of bubble sorting in bash is given below:

my_array = ( 2 3 1 5 4 )

echo «Unsorted array:» $

for ( ( x = 0 ; x 5 ; x++ ) )

for ( ( y = 0 ; y 5 -i- 1 ; y++ ) )

my_array [ $ ( ( y+ 1 ) ) ] = $temp

echo “Sorted array:” $

12.3 Example 3: Multidimensional Arrays in Bash:

Multidimensional arrays are not the official part of the Bash programming language. But Bash supports the major programming structures, most importantly loops. Multidimensional arrays can easily be simulated using “for” loops:

declare -a my_array

echo «Enter the number of rows»

echo «Enter the number of columns»

for ( ( x = 0 ; x rows; x++ ) )

for ( ( y = 0 ; y cols; y++ ) )

my_array [ $ , $ ] = $RANDOM #Assigning a random number

for ( ( i = 0 ; i rows; i++ ) )

for ( ( y = 0 ; y cols; y++ ) )

The above code takes rows and columns as input from the user then generates a pseudo-random number from 0-32767.

12.4 Example 4: Formatting a Poem in Bash:

The following example is another implementation of the array. The script is taking stanza lines as input from the user, format them, and print the entire stanza in the standard output:

echo «Enter First line of stanza»

echo «Enter Second line of stanza»

echo «Enter third line of stanza»

echo «Enter fourth line of stanza»

echo «Enter the name of the author»

for i in 1 2 3 4 #Getting four lines of the stanza

echo -e » \e[3m $ \e[10m» #Making the text italic

echo -e » \e[4m $ \e[10m» #Underlining the text

Conclusion:

The array is one of the critical structures in any programming language. It allows to store different elements of the same data type in a single variable, and those elements can be accessed through index position. Arrays are used in data structure, hash tables, linked lists, or search trees.

Linux is growing, though it has a very small desktop computer market. The primary source to interact with the Linux kernel is the shell. Shell is an interface that assists a user to communicate with the Linux system’s kernel. There are various types of shells, but the widely adopted shell is the Bourne Again Shell, also known as Bash. Bash takes command as input from the user and interprets it for the kernel to perform a task.

Similarly, to execute multiple commands or perform a specific task, Bash scripting is used. Bash scripting is also called shell scripting and uses Bash programming language, which is no less than any other scripting language. Like any other programming language, Bash includes everything such as variable defining, conditional statements, and loops. The array is an important data structure that is used to manage the data.

The function of arrays in Bash scripting is the same as other programming languages. But still, arrays are not as advanced in Bash as other scripting or programming languages.

Bash offers two types of arrays, indexed array and associative arrays. Associative arrays were introduced in the fourth version of bash. In the indexed array, the indexes are numeric, whereas, in associative arrays, indexes can be strings. The indexes of associative arrays are also called keys.

Bash provides various array modification options such as inserting an element, deleting an element, replacing an element, and accessing an element at a specific index. Bash arrays can have multiple uses, playlists in music players, and contacts in your contact list are examples of usage of an array. Moreover, arrays can be used as data management, stacks, queues, heaps, etc.

In Bash, arrays are not as powerful as in other programming languages. There are multiple reasons: Bash is not an object-oriented programming language, the syntax is hard to learn, slow execution time, and vulnerable to errors. Additionally, it does not support multidimensional arrays.

Despite that, arrays can be useful in performing various tasks such as parameter sweep, log alerting while performing cronjobs, and many other programming logic.

About the author

Sam U

I am a professional graphics designer with over 6 years of experience. Currently doing research in virtual reality, augmented reality and mixed reality.
I hardly watch movies but love to read tech related books and articles.

Источник

Читайте также:  Lazesoft windows recovery home инструкция
Оцените статью