Day 3 โ User Input and Comments
In case youโd like to revisit or catch up on what we covered on Day Two, hereโs the link:
https://dev.to/babsarena/learn-bash-scripting-with-me-day-2-36k0
When writing Bash scripts, itโs often useful to get input directly from the user. This allows your script to be interactive and dynamic. Letโs walk through how to use the "read" command in Bash to achieve this.
The below would clearly explain what you see in the image above.
1. Declaring the Shell
Every Bash script should start by declaring the shell that will interpret the script. We do this using the shebang:
#!/bin/bash
This tells the system to use Bash when executing the script.
2. Using read with -p
The read command is used to take input from the user.
Adding the -p option lets you display a prompt before the input is taken.
you will understand this better when you run the script, itโs almost the same thing as using the command echo.
Example:
#!/bin/bash
read -p "Please enter your name: " NAME
echo "Your name is $NAME"
Explanation
read -p "Enter your name: " โ Displays the text before waiting for user input.
NAME โ The variable where the input is stored.
echo "Your name is $NAME" โ Prints the stored input.
PS- Run the script and show your outcome.
3. Adding Comments
Comments are basically used to describe something in your own word, which is basically you leaving a comment in the script so you can make your script more readable or explanatory for other people and this is done using โ#โ and it tells the script not to add it to the list of things to run.
Just as seen in the image below:
Example:
#!/bin/bash
# This script asks the user for their name
read -p "Enter your name: " NAME
# Output the name back to the user
echo "Your name is $NAME"
NB- Anything after # is ignored by the script when it runs.
4. Another Way to Use read (Multiple Variables)
Instead of using -p, you can first use echo to display instructions, and then use read to take multiple inputs at once.
Example:
#!/bin/bash
# Ask for first name and last name
echo "Kindly enter your first name and last name: "
read FNAME LNAME
echo "Your name is $FNAME $LNAME"
Explanation
echo "Enter your first name and last name: " โ Displays a message.
read FNAME LNAME โ Takes two inputs: the first is stored in FNAME, the second in LNAME.
echo then displays both variables.
My outcome is shown below
5. Donโt Forget Executable Permission
Before running your script, make sure it has executable permissions:
chmod +x script.sh
Then run it:
./script.sh
Top comments (0)