Skip to content

Instantly share code, notes, and snippets.

@crh0831
Last active April 7, 2021 20:14
Show Gist options
  • Save crh0831/a4eaa91fb4eed1859ba73c2407afcd6a to your computer and use it in GitHub Desktop.
Save crh0831/a4eaa91fb4eed1859ba73c2407afcd6a to your computer and use it in GitHub Desktop.
BASH Challenges

BASH Challenges


  1. 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
  2. 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
  3. 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]}"
    done

    Example Output:

    Service: apache_https        Port 443
    Service: telnet              Port 23
    Service: ssh         Port 22
    Service: apache_http         Port 80
    
  4. 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]
    
  5. 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,...,1
    

    Example 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 ""; done

    Example 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
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment