How to Create a List in Bash Scripts? [2 Easy Methods]

In Bash, there is no data type named “list”, but you can generate a list using bash scripts that you can use for your needs. Also, sometimes associative arrays are referred to as lists in Bash scripting. In this article, I will demonstrate how to create a list in Bash scripts and give some examples.

Key Takeaways

  • Learning to generate a list using Bash script.
  • Learning to use loops and arrays to generate a list and know which to use when.

Free Downloads

2 Methods to List in Bash Scripts

In this article, you are going to learn how to use loops and arrays to generate lists using Bash script. You can use either of the methods to create a list. Also, you will notice that while using an array, I have written all the contents of the list inside the array. On the other hand, when I used loops, the list was generated by the loop.

You can read our Comparative Analysis of Methods to distinguish between these three methods and pick the best one for your needs.

Method 1: Generate a List with Loops Using Bash Scripts

In this method, you will see how to generate a list using for and while loops. Also, I have tried to make this list generation interactive, so that users can use it according to their needs.

Case 1: List Files with for Loop Using Bash Script

Suppose, I want to list files with “employee” in the name. To do so I’ve used for loop to go through the files in loops. If you want to achieve this, follow the below steps.

Steps to Follow >

First, launch the Ubuntu terminal. However, you can use the shortcut keys CTRL+ALT+T to do so.

➋ Then create a file with the extension .sh using the nano command and open the script in the text editor like the following.

nano list_files.sh
EXPLANATION
  • nano: Opens and creates a file in the nano text editor.
  • list_files.sh: File name.

➌ After that, copy the following script into your text editor.

#!/bin/bash

#listing all files named employee
for a in $(ls employee*)
do
            ls -l "$a"
done
EXPLANATION

The first line, #!/bin/bash is called shebang, which specifies the interpreter as Bash, which will be used to execute the script. Then, the for loop iterates over the list of files in the current directory that contain the name “employee” and the output is captured and processed by the loop. After that, the line ls -l “$a” basically executes the ls -l command for each file captured by the loop and displays detailed information about the file, including its permission, owner, size, and modification timestamp. Finally, the “$a” is to represent the current file being processed in each iteration.

➎ Now, you need to make the bash script file executable. Type the following line in the terminal to do so.

chmod +x list_files.sh
EXPLANATION
  • chmod: Changes the permissions of files and directories.
  • +x: Argument with the chmod command to add the executable permission.
  • list_files.sh: File that you want to make executable.

➏ Finally, you can simply run the file from your command line by executing:

./list_files.sh

list all files that contains employee in their namesAfter running the script, it printed the list of files containing employees in them.

Case 2: List Numbers with while Loop Using Bash Script

In this case, I will show you how to generate a list of numbers using a while loop. Also, to make this script more interactive, the list of numbers will take user input. So, you can get the list of numbers according to your choice.

You can follow the steps mentioned in case 1 of method 1, to know how to write, execute, and run the bash script.

Script (list_numbers.sh) >

#!/bin/bash

#Prompt user to enter the number of iterations
read -p "Enter the number of iterations: " total_iterations
i=1 #current iteration

# Start the loop
while [ $i -le $total_iterations ]
do
   echo "$i"  # Print the current iteration
   ((i++))     # Increment the counter variable
done
EXPLANATION

As in the first script, this code starts with #!/bin/bash, which specifies the Bash interpreter. The next line prompts the user to enter the number of iterations and store it in the variable named total_iterations. Then i=1 is used to declare and initialize the variable i to 1 which represents the current iteration. After that, a while loop continues until the value i is less than or equal to the total_iterations. The ((i++)) actually increments the value of i by 1, moving to the next iteration. Finally, the echo command prints the value of each and every iteration until the end of the loop.

Use this command to run the script:

./list_numbers.sh

Generate list of numbers in Bash using iteration After running the script, a user prompt takes the iteration number from the user. According to the inserted number, the script prints numbers. For example, as I entered 7, it showed a list of numbers from 1 to 7.

Method 2: List Name of Months Using Arrays in Bash Scripts

In this method, I have demonstrated the process of generating any list using an array. I have generated a list of months. Moreover, you can use the array to generate any list you want, you just have to change the list’s contents.

You can follow the steps mentioned in case 1 of method 1, to know how to write, execute, and run the bash script.

Script (list_months.sh) >

#!/bin/bash

# Declare an array of month names
Months=("January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December")

# Print the list of months
echo "The list of Months: ${Months[@]}"
EXPLANATION

This script starts with #!/bin/bash, which specifies the Bash interpreter. The next line declares an array named Months, which contains the names of months. Finally, the echo command prints the list of months, and ${Months[@]} expands the array to include all elements.

Use this command to run the script:

./list_months.sh

Generate list of months using arrayAfter running the script, it prints the list of months given inside the array.

Comparative Analysis of the Methods

In this section, I will give you a comparative analysis of the two methods mentioned above so you can understand which will be best for you to use.

Methods Pros Cons
Method 1
  • The list is automatically generated by loops.
  • Those who have little to no knowledge of programming can find it complicated to write scripts using loops.
Method 2
  • If you generate a  list using arrays, it is relatively simple, as you just have to know array syntax.
  • The contents of the list have to be given inside the array.

If you want to generate a list automatically, you better use the first method, but you must have a firm understanding of conditional loops. On the other hand, if you already have a list and want to manipulate it and print it in different ways, you should go for the second method.

Conclusion

So far, you’ve learned to generate a list with Bash scripting. Using loops or arrays, you can now quickly create lists. Choose the one that best suits your needs. Feel free to ask any questions regarding this article.

People Also Ask

What is the command to list bash?
The command ls is used to list in Bash. This command is specifically used for making a list of directories and files.

How do you define a list in a Bash script?
A list is basically an associative array in Bash scripting. So, defining a list means declaring an array in Bash. The syntax to declare an array in Bash is, array_name={“element1” “element2”….”element_n”}.

How do I print all list elements in Bash?
You can use the command declare with the option -p, if you want to print all elements of a Bash array. So, the syntax is declare -p Array_name.

How do I list all users in Bash?
To list all users in Bash, you can use the command cat along with /etc/passwd. So, this passwd file in etc directory actually contains all user names and when you execute this, you can see all user names printed on your screen.

Related Articles


<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial

Rate this post
Lamisa Musharrat

Hello there. My name is Lamisa Musharat, and I'm an Linux Content Developer Executive at SOFTEKO. I earned a bachelor's degree in Naval Architecture and Marine Engineering from Bangladesh University of Engineering and Technology (BUET).I learned Linux out of my curiosity and now I find it useful as automation is easier using Linux. I take great pleasure in assisting others with Linux-related issues. I really want you to enjoy and benefit from my efforts.Read Full Bio

Leave a Comment