It is recommended to go through Array Basics Shell Scripting | Set-1 Introduction Suppose you want to repeat a particular task so many times then it is a better to use loops. Mostly all languages provides the concept of loops. In Bourne Shell there are two types of loops i.e for loop and while loop. To Print the Static Array in Bash 1. By Using while-loop ${#arr[@]} is used to find the size of Array.
bash
arr=(1 12 31 4 5)
i=0
while [ $i -lt ${
do
echo ${arr[$i]}
i=`expr $i + 1`
done
|
Output:
1
2
3
4
5
Time Complexity: O(n)
Auxiliary Space: O(1)
2. By Using for-loop
bash
arr=(1 2 3 4 5)
for i in "${arr[@]}"
do
echo $i
done
|
Output:
1
2
3
4
5
Time Complexity: O(n)
Auxiliary Space: O(1)
To Read the array elements at run time and then Print the Array. 1. Using While-loop
bash
echo -n "Enter the Total numbers :"
read n
echo "Enter numbers :"
i=0
while [ $i -lt $n ]
do
read a[$i]
i=`expr $i + 1`
done
echo "Output :"
i=0
while [ $i -lt $n ]
do
echo ${a[$i]}
i=`expr $i + 1`
done
|
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Using for-loop
bash
echo -n "Enter the Total numbers :"
read n
echo "Enter numbers:"
i=0
while [ $i -lt $n ]
do
read a[$i]
i=`expr $i + 1`
done
echo "Output :"
for i in "${a[@]}"
do
echo $i
done
|
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5
Time Complexity: O(n)
Auxiliary Space: O(1)
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
18 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...