This section provides real-world case studies and practical examples to reinforce your understanding of Bash scripting concepts.
In this example, we'll create a simple Bash script to understand the basic structure and execution of scripts.
#!/bin/bash
# Your script code here
echo "Hello, World!"
Explore how to manipulate files and directories using Bash scripting.
#!/bin/bash
# Your script code here
mkdir my_directory
cd my_directory
touch new_file.txt
Learn how to use arrays in Bash scripts.
#!/bin/bash
# Your script code here
fruits=("Apple" "Banana" "Orange")
for fruit in "${fruits[@]}"; do
echo "I like $fruit"
done
See examples of advanced control structures, including nested loops and conditionals.
#!/bin/bash
# Your script code here
for ((i=1; i<=5; i++)); do
for ((j=1; j<=i; j++)); do
echo -n "* "
done
echo
done
Learn how to validate user input and handle errors gracefully.
#!/bin/bash
# Your script code here
read -p "Enter a number: " num
if ! [[ "$num" =~ ^[0-9]+$ ]]; then
echo "Error: Not a valid number."
exit 1
fi
echo "You entered: $num"
Build a simple menu system for user interaction.
#!/bin/bash
# Your script code here
echo "Choose an option:"
select option in "Option 1" "Option 2" "Option 3"; do
case $option in
"Option 1") echo "You selected Option 1"; break;;
"Option 2") echo "You selected Option 2"; break;;
"Option 3") echo "You selected Option 3"; break;;
*) echo "Invalid option";;
esac
done
Explore text processing using the awk
command in Bash scripts.
#!/bin/bash
# Your script code here
echo "John Doe,25" | awk -F ',' '{print "Name: " $1, "Age: " $2}'
Learn how to perform recursive file operations, such as searching for files in nested directories.
#!/bin/bash
# Your script code here
find . -type f -name "*.txt" -exec echo "Found file: {}" \;
Understand how to work with background processes and job control in Bash.
#!/bin/bash
# Your script code here
./background_process.sh &
echo "Script continues while background process runs."
Create an interactive script that takes user input and provides real-time feedback.
#!/bin/bash
# Your script code here
read -p "Enter your name: " name
echo "Hello, $name! Welcome to the interactive script."
These examples cover various aspects of Bash scripting, from basic structures to more advanced concepts. Use them as templates and modify them according to your specific scripting needs.
Continue to Part 11: Additional Resources.
Go back to Bash Scripting Guide.
Visit other Developer Guides.