Building and running a shell script
Objective: Write your first shell script and learn basic commands.
Tasks:
- Open your terminal.
- Create a new directory called
shell_scriptingand navigate into it. - Create a file named
hello_world.sh. - Use a text editor (like
nanoorvim) to add the following script to the file:#!/bin/bash echo "Hello, World!"
- Make the script executable with the command
chmod +x hello_world.sh. - Run the script using
./hello_world.sh. - Modify the script to also print the current date and time.
Objective: Learn to use variables and take user input in a shell script.
Tasks:
- Create a new file named
greet_user.sh. - Write a script that asks the user for their name and greets them:
#!/bin/bash echo "What is your name?" read name echo "Hello, $name! Nice to meet you."
- Make the script executable and run it.
- Extend the script to ask for the user's age and print it along with the greeting.
Objective: Use conditional statements to control the flow of your script.
Tasks:
- Create a new file named
check_age.sh. - Write a script that asks the user for their age and checks if they are eligible to vote (age 18 or older):
#!/bin/bash echo "How old are you?" read age if [ "$age" -ge 18 ]; then echo "You are eligible to vote." else echo "You are not eligible to vote yet." fi
- Make the script executable and run it.
- Modify the script to also check if the user is a teenager (age between 13 and 19).
Loops and Functions
Objective: Learn to use loops and functions in your shell script.
Tasks:
- Create a new file named
countdown.sh. - Write a script that counts down from 5 to 1 and then prints "Blast off!":
#!/bin/bash for ((i=5; i>=1; i--)); do echo $i sleep 1 done echo "Blast off!"
- Make the script executable and run it.
- Add a function to the script that prints a custom message before the countdown starts. Call this function at the beginning of the script.
By completing these four parts, you'll have a good understanding of the basics of shell scripting, including writing scripts, using variables, taking user input, conditional statements, loops, and functions. Good luck!
Come up with your own script and what would you like a script to do?
We are curious about what you like to run in a script!