A list is an abstract data structure that stores elements in an ordered manner, making it super-efficient when retrieving. It may sound a bit disappointing if you want to use the lists in a Linux shell, but a built-in list data structure is not supported in a Linux shell. However, a few workarounds of it can serve as the lists. One of them is an array or command substitution. How do I use them? Read towards the end.
This guide explains the alternatives of the list data structure that can be used on Linux shell.
- Arrays
- Command Substitution
How to Use Arrays in Linux Shell?
One way to work with lists in the shell is to use arrays. Arrays in the shell can be considered a list of elements. It can be created and manipulated using various commands and techniques.
The Linux shell supports arrays which are variables having multiple values. These values can be of the same or different data types since the shell treats everything as a string.
To create an array in the shell, use this syntax:
my_array=(item1 item2 item3 item4 item5)
Here, my_array initializes the array while “item1 – item5” are the elements in the array. Let’s display each of them:
$ echo ${my_array[0]}
The above command only displays only one element of the array. To print all the elements in the array, use the for loop like this:
$ for item in ${my_array[@]};
do
echo $item;
done
It can also be used in the bash scripts like this and for that, this script is used:
#!/bin/sh
NAME[0]="John"
NAME[1]="Joe"
NAME[2]="Tom"
NAME[3]="Daisu"
NAME[4]="Doe"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
Let’s execute the above-created script using this command:
$ bash myscript.sh
The above image displays the elements at “Index 0 and Index 1.”
What is Command Substitution, and How to Use it?
Another thing to somehow get the functionality of lists in the Linux shell is the command substitution. It allows users to use the output of a command as input to another command. This can be useful when working with lists of files. Let’s view the list of all files and folders in the current directory; you can navigate through the directories using the cd command:
$ for file in $files; do
echo $file
done
The above image displays all the files and folders in the “/home/itslinuxfoss” directory.
Conclusion
No, the Linux shell does not support list data structures, but it does support arrays that can somehow function as lists. The Linux shell supports arrays which are variables having multiple values. These values can be of the same or different data types since the shell treats everything as a string. Another method is command substitution which allows users to use the output of a command as input to another command.
This guide answered if the Linux shell does not support list data structure.
TUTORIALS ON LINUX, PROGRAMMING & TECHNOLOGY