0% found this document useful (0 votes)
9 views17 pages

Essential Bash Script Examples

The document provides a comprehensive collection of Bash script examples, ranging from basic to advanced levels. It includes scripts for common tasks such as file manipulation, user input handling, arithmetic operations, and system monitoring. Each example is accompanied by a brief description of its functionality.

Uploaded by

kombi20025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views17 pages

Essential Bash Script Examples

The document provides a comprehensive collection of Bash script examples, ranging from basic to advanced levels. It includes scripts for common tasks such as file manipulation, user input handling, arithmetic operations, and system monitoring. Each example is accompanied by a brief description of its functionality.

Uploaded by

kombi20025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic Bash Script Examples

1. Hello World Script


#!/bin/bash
echo "Hello, World!"
2. Check if a file exists
#!/bin/bash
if [[ -f "[Link]" ]]; then
echo "File exists."
else
echo "File does not exist."
fi
3. Print numbers from 1 to 10 using a for loop
#!/bin/bash
for i in {1..10}; do
echo $i
done
4. Take user input
#!/bin/bash
read -p "Enter your name: " name
echo "Hello, $name!"
5. Check if a directory exists
#!/bin/bash
if [ -d "mydir" ]; then
echo "Directory exists."
else
echo "Directory does not exist."
fi
6. Print all arguments passed to the script
#!/bin/bash
echo "Arguments passed: $@"
7. Display current date and time
#!/bin/bash
echo "Current date and time: $(date)"
8. Simple arithmetic
#!/bin/bash
result=$((3 + 2))
echo "3 + 2 = $result"
9. Count lines in a file
#!/bin/bash
wc -l < [Link]
10. Rename all .txt files to .bak
#!/bin/bash
for file in *.txt; do
mv "$file" "${file%.txt}.bak"
done

Intermediate Bash Script Examples


11. Process command-line arguments
#!/bin/bash
for arg in "$@"; do
echo "Processing $arg"
done
12. Check if a number is even or odd
#!/bin/bash
read -p "Enter a number: " num
if (( num % 2 == 0 )); then
echo "$num is even."
else
echo "$num is odd."
fi
13. Calculate factorial using a while loop
#!/bin/bash
read -p "Enter a number: " num
factorial=1
while (( num > 1 )); do
factorial=$((factorial * num))
((num--))
done
echo "Factorial: $factorial"
14. Countdown timer
#!/bin/bash
for ((i=10; i>0; i--)); do
echo $i
sleep 1
done
echo "Time's up!"
15. Read a file line by line
#!/bin/bash
while read -r line; do
echo $line
done < [Link]
16. Print a multiplication table
#!/bin/bash
read -p "Enter a number: " num
for ((i=1; i<=10; i++)); do
echo "$num * $i = $((num * i))"
done
17. Find the largest of three numbers
#!/bin/bash
read -p "Enter three numbers: " a b c
if ((a > b && a > c)); then
echo "Largest is $a"
elif ((b > c)); then
echo "Largest is $b"
else
echo "Largest is $c"
fi
18. Check if a string is a palindrome
#!/bin/bash
read -p "Enter a string: " str
if [[ $str == $(echo $str | rev) ]]; then
echo "$str is a palindrome."
else
echo "$str is not a palindrome."
fi
19. Simple menu-driven program
#!/bin/bash
echo "1. Show date"
echo "2. List files"
echo "3. Exit"
read -p "Choose an option: " choice
case $choice in
1) date ;;
2) ls ;;
3) exit ;;
*) echo "Invalid option" ;;
esac
20. Extract fields from a CSV file
#!/bin/bash
while IFS=, read -r name age; do
echo "Name: $name, Age: $age"
done < [Link]

Advanced Bash Script Examples


21. Monitor disk usage and send alert
#!/bin/bash
threshold=80
usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if (( usage > threshold )); then
echo "Disk usage is above $threshold%. Current usage:
$usage%"
fi
22. Multi-level nested loops
#!/bin/bash
for i in {1..3}; do
for j in {1..3}; do
echo "$i, $j"
done
done
23. Backup files using a timestamp
#!/bin/bash
backup_dir="backup_$(date +%Y%m%d_%H%M%S)"
mkdir "$backup_dir"
cp *.txt "$backup_dir"
24. Validate an IP address
#!/bin/bash
read -p "Enter an IP address: " ip
if [[ $ip =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
echo "Valid IP address."
else
echo "Invalid IP address."
fi
25. Find prime numbers up to N
#!/bin/bash
read -p "Enter N: " n
for ((i=2; i<=n; i++)); do
is_prime=1
for ((j=2; j*j<=i; j++)); do
if ((i % j == 0)); then
is_prime=0
break
fi
done
((is_prime)) && echo $i
done
26. Send an email alert
#!/bin/bash
subject="Alert!"
message="Disk usage is high."
recipient="admin@[Link]"
echo "$message" | mail -s "$subject" "$recipient"
27. File compression script
#!/bin/bash
for file in *.log; do
gzip "$file"
done
28. Parallel processing with &
#!/bin/bash
for url in "[Link] "[Link] do
curl -O "$url" &
done
wait
29. Automated file cleanup
#!/bin/bash
find /path/to/dir -type f -mtime +30 -delete
30. Check system memory usage
#!/bin/bash
memory=$(free | awk '/Mem/ {print $3/$2 * 100.0}')
echo "Memory usage: $memory%"
Let’s dive deeper into some additional examples, focusing on
testing with [[ ]], arithmetic with (( )), loops, and
conditionals. Here are more examples:

Additional Intermediate Examples


31. Check if a number is positive, negative, or zero
#!/bin/bash
read -p "Enter a number: " num
if (( num > 0 )); then
echo "Positive"
elif (( num < 0 )); then
echo "Negative"
else
echo "Zero"
fi
32. Compare two strings
#!/bin/bash
read -p "Enter first string: " str1
read -p "Enter second string: " str2
if [[ $str1 == $str2 ]]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi
33. Sum of digits in a number
#!/bin/bash
read -p "Enter a number: " num
sum=0
while (( num > 0 )); do
digit=$(( num % 10 ))
sum=$(( sum + digit ))
num=$(( num / 10 ))
done
echo "Sum of digits: $sum"
34. Check if a year is a leap year
#!/bin/bash
read -p "Enter a year: " year
if (( year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ));
then
echo "$year is a leap year."
else
echo "$year is not a leap year."
fi
35. Check if a file is readable, writable, and executable
#!/bin/bash
read -p "Enter a file name: " file
if [[ -r $file && -w $file && -x $file ]]; then
echo "$file is readable, writable, and executable."
else
echo "$file does not have all permissions."
fi
36. Create a file only if it doesn’t already exist
#!/bin/bash
file="[Link]"
if [[ -e $file ]]; then
echo "$file already exists."
else
touch "$file"
echo "$file created."
fi
37. Case-insensitive string comparison
#!/bin/bash
read -p "Enter first string: " str1
read -p "Enter second string: " str2
if [[ ${str1,,} == ${str2,,} ]]; then
echo "Strings are equal (case-insensitive)."
else
echo "Strings are not equal."
fi
38. Validate a file path
#!/bin/bash
read -p "Enter a file path: " filepath
if [[ -e $filepath ]]; then
echo "Path exists."
else
echo "Path does not exist."
fi
39. Loop through an array
#!/bin/bash
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo "$fruit"
done
40. Countdown using a while loop
#!/bin/bash
count=10
while (( count > 0 )); do
echo "$count"
((count--))
done
echo "Done!"

Additional Advanced Examples


41. Fibonacci sequence up to N terms
#!/bin/bash
read -p "Enter the number of terms: " n
a=0
b=1
echo "$a"
echo "$b"
for ((i=3; i<=n; i++)); do
c=$((a + b))
echo "$c"
a=$b
b=$c
done
42. Check if a string contains a substring
#!/bin/bash
read -p "Enter a string: " str
read -p "Enter a substring: " substr
if [[ $str == *"$substr"* ]]; then
echo "Substring found."
else
echo "Substring not found."
fi
43. Delete empty files in a directory
#!/bin/bash
find /path/to/directory -type f -empty -delete
44. Rename files with a specific pattern
#!/bin/bash
for file in *.txt; do
mv "$file" "new_$file"
done
45. Generate random passwords
#!/bin/bash
length=12
password=$(tr -dc 'A-Za-z0-9!@#$%^&*()_' < /dev/urandom |
head -c $length)
echo "Generated password: $password"
46. Send a notification when a process completes
#!/bin/bash
long_running_task & # Replace with your actual command
wait
echo "Task completed!" | mail -s "Notification"
user@[Link]
47. Simulate rolling a die
#!/bin/bash
roll=$((RANDOM % 6 + 1))
echo "You rolled a $roll"
48. Measure script execution time
#!/bin/bash
start=$(date +%s)
# Your script logic here
sleep 2
end=$(date +%s)
echo "Execution time: $((end - start)) seconds"
49. Monitor CPU usage in real-time
#!/bin/bash
while true; do
top -bn1 | grep "Cpu(s)"
sleep 2
done
50. Check if a process is running
#!/bin/bash
read -p "Enter process name: " process
if pgrep "$process" > /dev/null; then
echo "$process is running."
else
echo "$process is not running."
fi
51. Check password hash with sha256
#!/bin/bash
#verifier le mot de pass

echo -e "Enter your password \n"


read pass
userpass="$(echo $pass | sha256sum)"
systempass="$(echo p@ssw0rd | sha256sum)"
if [[ "$userpass" == "$systempass " ]] ;then
echo "Exactly !!!"
else
echo "No, try again another time"
fi

Common questions

Powered by AI

A Bash script can create a multiplication table by using a 'for' loop that iterates over numbers 1 to 10. The script prompts for a number, and within the loop, it multiplies the input number by each iterator value, displaying the results: #!/bin/bash read -p "Enter a number: " num for ((i=1; i<=10; i++)); do echo "$num * $i = $((num * i))" done

In Bash scripting, you can check if a number is even or odd by using the modulo operator (%). For instance, you can prompt the user to enter a number, and then check if the remainder when divided by 2 is zero. If the remainder is zero, the number is even; otherwise, it is odd. The script would look like this: #!/bin/bash read -p "Enter a number: " num if (( num % 2 == 0 )); then echo "$num is even." else echo "$num is odd." fi

To check system memory usage with a Bash script, use the 'free' command to extract memory metrics. You calculate the percentage of used memory by dividing used memory by total memory and multiplying by 100. This approach uses 'awk' for parsing the 'free' command output: #!/bin/bash memory=$(free | awk '/Mem/ {print $3/$2 * 100.0}') echo "Memory usage: $memory%"

A Bash script can convert a string to lowercase for case-insensitive comparison using the 'tr' command or parameter expansion with ',,'. In a script, after reading input strings, convert both to lowercase using '${variable,,}' before comparison. This ensures that the comparison disregards letter casing: #!/bin/bash read -p "Enter first string: " str1 read -p "Enter second string: " str2 if [[ ${str1,,} == ${str2,,} ]]; then echo "Strings are equal (case-insensitive)." else echo "Strings are not equal." fi

To read and process each field from a CSV file with a Bash script, the 'while read' loop and 'IFS' (Internal Field Separator) are used to split CSV lines into variables for processing. For instance, if a CSV file contains names and ages, you can process them like this: #!/bin/bash while IFS=, read -r name age; do echo "Name: $name, Age: $age" done < data.csv

To rename all '.txt' files to '.bak' in a directory using a Bash script, a 'for' loop iterates over all '.txt' files. The 'mv' command is used to rename each file within the loop by modifying its extension from '.txt' to '.bak': #!/bin/bash for file in *.txt; do mv "$file" "${file%.txt}.bak" done

To validate an IP address format using a Bash script, regular expressions can be employed to match the typical structure of an IP address: four octets separated by dots, with each octet ranging from 0 to 255. The script prompts for an IP address input, checks it against the regular expression, and provides feedback on its validity. Here's a sample snippet: #!/bin/bash read -p "Enter an IP address: " ip if [[ $ip =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then echo "Valid IP address." else echo "Invalid IP address." fi

To create a Bash script that checks if a file is readable, writable, and executable, you can use test operators with the '-r', '-w', and '-x' flags, respectively, in a conditional expression. First, prompt the user to enter the file name. Then, check each permission using the appropriate flag: '-r' for readability, '-w' for writability, and '-x' for executability. The script prints a confirmation message if the file has all three permissions, otherwise it indicates the lack of some permissions: #!/bin/bash read -p "Enter a file name: " file if [[ -r $file && -w $file && -x $file ]]; then echo "$file is readable, writable, and executable." else echo "$file does not have all permissions." fi

To check if a string is a palindrome using a Bash script, read the string input from the user. Reverse the string using 'echo' and 'rev', then compare the original and reversed strings. If they match, the string is a palindrome: #!/bin/bash read -p "Enter a string: " str if [[ $str == $(echo $str | rev) ]]; then echo "$str is a palindrome." else echo "$str is not a palindrome." fi

A Bash script can monitor disk usage using the 'df' command, which displays filesystem disk space usage. By setting a usage threshold, for instance, 80%, the script can alert the user when this threshold is exceeded. It extracts the usage percentage from the command's output using 'awk' and 'tr' to parse and clean the percentage value. If the usage surpasses the threshold, a warning message is printed: #!/bin/bash threshold=80 usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%') if (( usage > threshold )); then echo "Disk usage is above $threshold%. Current usage: $usage%" fi

You might also like