2.8 KiB
BASH Challenges
These are examples of scripting challenges I was given and helped create for interviewees
-
Check for the presence of a directory and create it if it doesn't exist
Example Solution
devdir="/mnt/sqlback1/LSQLSHARE01DEV" if [[ ! -d "${devdir}" ]]; then echo "${devdir} not found." # Create Directory mkdir -p "${devdir}" fi -
Given a threshold, determine if a given directory size is over the threshold.
Example Solution
dir="/mnt/data2/backups" threshold="100000000" # 100GB dirsize=$(/usr/bin/du -s ${dir} | awk '{print $1}') if [[ $dirsize -gt $threshold ]]; then echo "Threshold Exceeded" /usr/bin/du -hs "${dir}" fi -
Create and loop over an associative array. Ex. create an array of services and ports then print them
Example Solution
# Declare service names and ports in an array declare -A services=( [apache_http]=80 [apache_https]=443 [ssh]=22 [telnet]=23 ) # Iterate over services and ports for p in "${!services[@]}"; do echo -e "Service: ${p} \t Port ${services[$p]}" doneExample Output:
Service: apache_https Port 443 Service: telnet Port 23 Service: ssh Port 22 Service: apache_http Port 80 -
Write a short script that displays the numbers 2 through 128 in brackets (even numbers only, as seen below).
[2] [4] [8] [16] [32] [64] [128]Example Solution
i=1; while [ $i -lt 65 ]; do let i=$((i+i)); print "[$i]"; done```Example Output
[2] [4] [8] [16] [32] [64] [128] -
Write a script that, for each number from 1 to 100, prints a comma-delimited list of numbers in descending order from the current number to 1. Each list should be shown on a separate line as seen below.
1 2,1 3,2,1 4,3,2,1 ... 100,99,...,1Example Solution (from 10 to save space). (OK, I cheated shaving off the trailing comma.)
echo "1"; for x in {2..10}; do for i in {$x..2}; do echo -n $i,; done; echo -n "1"; echo ""; doneBest Solution:
for (( i=1;i<=10;i++ )); do eval printf -- '%d\\n' "{${i}..1}" | paste -sd ',' -;doneExample Output
1 2,1 3,2,1 4,3,2,1 5,4,3,2,1 6,5,4,3,2,1 7,6,5,4,3,2,1 8,7,6,5,4,3,2,1 9,8,7,6,5,4,3,2,1 10,9,8,7,6,5,4,3,2,1
Tags: howto