Here are the simple steps to create a bash script that asks the user’s favorite color and prints it.
1. Create a new file as mentioned below.
vi favorite_color_script.sh
2. Copy and paste below simple Bash script that prompts the user for their favorite color and then prints it:
#!/bin/bash # This script asks the user for their favorite color and prints it. # Prompt the user for input echo "What is your favorite color?" # Read the user's input into the variable 'favorite_color' read -p "Enter your favorite color: " favorite_color # Print the user's favorite color echo "Your favorite color is: $favorite_color"
Explanation of the script:
“#!/bin/bash”: This line is called a shebang, and it tells the system to execute the script using the Bash shell.
“echo “What is your favorite color?”“: Prints a message asking the user for their favorite color.
“read -p “Enter your favorite color: ” favorite_color”: Uses the “read” command to take user input, with the “-p” option providing a prompt message. The user’s input is stored in the variable “favorite_color”.
“echo “Your favorite color is: $favorite_color”“: Prints the user’s favorite color using the value stored in the “favorite_color” variable.
3. Save and close the “vi” editor by pressing “Esc” key and type :wq!
4. Make sure to save the script in a file (e.g., “favorite_color_script.sh”) and give it execution permissions with the following command:
chmod +x favorite_color_script.sh
You can then run the script by executing:
./favorite_color_script.sh
The script will prompt the user for their favorite color, and then it will print the entered color.
How do you feel about this post? Drop your comments below..