Bash script samples
Bash scripting is a powerful tool for automating tasks and configuring environments in Unix-like systems. Here's a collection of bash style examples covering basic syntax, best practices, and various features of the Bash shell:
1. Basic Variables and Echo
#!/bin/bash
# Define variables
name="John"
age=30
# Print variables
echo "Hello, my name is $name, and I am $age years old."
2. Reading Input from User
#!/bin/bash
# Ask user for input
echo "Please enter your name:"
read name
# Greet user
echo "Hello, $name!"
3. Conditional Statements (If-Else)
#!/bin/bash
# Ask for the user's age
echo "Enter your age:"
read age
# Check if the user is old enough to drive
if [ $age -ge 18 ]; then
echo "You are old enough to drive."
else
echo "Sorry, you are not old enough to drive."
fi
4. Loops (For, While, Until)
For Loop
#!/bin/bash
# Print numbers from 1 to 5
for i in {1..5}
do
echo "Number $i"
done
While Loop
#!/bin/bash
# Ask user for a number and keep asking until it's greater than 10
while true; do
echo "Enter a number greater than 10:"
read num
if [ $num -gt 10 ]; then
echo "Good job!"
break
fi
done
Until Loop
#!/bin/bash
# Loop until the user enters 'exit'
while true; do
echo "Type 'exit' to stop the script"
read input
if [ "$input" == "exit" ]; then
echo "Exiting..."
break
fi
done
5. Functions
#!/bin/bash
# Function to greet a user
greet() {
echo "Hello, $1!"
}
# Call the function
greet "Alice"
6. Arrays
#!/bin/bash
# Declare an array
fruits=("apple" "banana" "cherry")
# Print an element of the array
echo "First fruit: ${fruits[0]}"
# Loop through array
for fruit in "${fruits[@]}"
do
echo "Fruit: $fruit"
done
7. File Operations
Check if File Exists
#!/bin/bash
# Check if a file exists
if [ -e "file.txt" ]; then
echo "file.txt exists!"
else
echo "file.txt does not exist."
fi
Create a File and Write to It
#!/bin/bash
# Create a file and write to it
echo "Hello, World!" > hello.txt
echo "This is a new file." >> hello.txt
# Display file contents
cat hello.txt
8. Redirecting Output
#!/bin/bash
# Redirect output to a file
echo "This is an output message" > output.txt
# Append output to a file
echo "This is an appended message" >> output.txt
# Redirect errors
non_existent_command 2> error.log
# Redirect both stdout and stderr to a file
some_command &> output_and_errors.log
9. Command Substitution
#!/bin/bash
# Get the current date and store it in a variable
current_date=$(date)
# Print the date
echo "Today's date is: $current_date"
10. Exit Status and Error Handling
#!/bin/bash
# Command with potential error
cp source.txt destination.txt
# Check exit status
if [ $? -eq 0 ]; then
echo "Command succeeded"
else
echo "Command failed"
fi
11. Using trap
for Signal Handling
#!/bin/bash
# Set a trap to handle SIGINT (Ctrl+C)
trap "echo 'You pressed Ctrl+C. Exiting...'; exit" SIGINT
echo "Running... Press Ctrl+C to stop."
# Sleep for 10 seconds to allow the user to press Ctrl+C
sleep 10
12. Using case
Statements
#!/bin/bash
# Ask the user for a choice
echo "Enter a number (1, 2, or 3):"
read num
# Use case to handle different choices
case $num in
1)
echo "You selected 1."
;;
2)
echo "You selected 2."
;;
3)
echo "You selected 3."
;;
*)
echo "Invalid selection."
;;
esac
13. Background Processes and Jobs
#!/bin/bash
# Run a command in the background
sleep 10 &
# Get the process ID of the last background process
echo "Process ID of last background command: $!"
# Wait for the background process to finish
wait
echo "Background process finished!"
14. Script Arguments
#!/bin/bash
# Check if user provided arguments
if [ $# -eq 0 ]; then
echo "No arguments provided."
exit 1
fi
# Display all arguments
echo "You provided the following arguments: $@"
15. Using test
for File Comparison
#!/bin/bash
# Check if a file is readable
if test -r "file.txt"; then
echo "The file is readable."
else
echo "The file is not readable."
fi
# Check if a file is empty
if [ ! -s "file.txt" ]; then
echo "The file is empty."
else
echo "The file has content."
fi
Best Practices for Bash Scripting
- Use Comments: Always comment your scripts to explain what each part does, especially if it's complex.
- Use
#!/bin/bash
: Specify the interpreter at the top of your script to ensure it runs with the correct shell. - Quote Your Variables: Always wrap variables in quotes to avoid issues with spaces or special characters.
echo "Hello, $name"
- Use
set -e
: Addset -e
at the top of your script to stop execution when a command fails.set -e
- Use Functions for Reusability: Group related code into functions for better maintainability and readability.
These are some basic examples and best practices for Bash scripting. You can extend them based on your use case, and you will find that Bash is very versatile for automation, system administration, and processing data.
댓글
댓글 쓰기