Essential Bash Script Examples
Essential Bash Script Examples
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