How to create Bash Script using Array on Debian 12
To Create Bash Script Using Array On Debian 12
Introduction
A Bash array is a variable that can hold multiple values, similar to arrays in other programming languages that allows you to store a collection of data elements under a single variable name. Arrays in Bash can be indexed and accessed using integers, and they are particularly helpful for organizing and manipulating sets of related data within shell scripts.
Procedure Steps
Step 1: Check the OS version by using the below command.
root@linuxhelp:~# cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
NAME="Debian GNU/Linux"
VERSION_ID="12"
VERSION="12 (bookworm)"
VERSION_CODENAME=bookworm
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
Step 2: Make a script by using the below command
root@linuxhelp:~# vim array
#!/bin/bash
# Create request for user creation to register
echo "The is the Process for Regitering"
read -p "what is your name: " name
# Create array with sports name
sport[0]="Cricket"
sport[1]="Footbal"
sport[2]="Chess"
sport[3]="Carrom"
sport[4]="Valleybal"
array_length=${#sport[@]} # To Store length of array
index=$(($RANDOM % $array_length)) # To Increase the array Randomly
# Ask to user for creation
echo "HI!" $name, "would you like to play ${sport[$index]}" "?(yes/no)" by default:yes # To Ask user's sport option
read -p "Answer: " answer # To get answer from user for sport
if [ "$answer" == "no" ] # If the answer is no
then
echo "You were not chose ${sport[$index]}" # It will print
else
echo "You were chose ${sport[$index]}" # It will pring
fi
Step 3: make the executable permission by using the below command
root@linuxhelp:~# chmod +x array
Step 4: Run the script by using the below command
root@linuxhelp:~# ./array
The is the Process for Regitering
what is your name: linuxhelp1
HI! linuxhelp1, would you like to play Footbal ?(yes/no) by default:yes
Answer: yes
You were chose Footbal
Step 5: Run the script by using the below command
root@linuxhelp:~# ./array
The is the Process for Regitering
what is your name: linuxhelp2
HI! linuxhelp2, would you like to play Chess ?(yes/no) by default:yes
Answer: no
You were not chose Chess
Conclusion:
We have reached the end of this article. In this guide, we have walked you through the steps required to create Bash Script using Array on Debian 12. Your feedback is much welcome.
Comments ( 0 )
No comments available