Files
MarkdownNotes/blog - BASH challenges.md
chawley 65c434952a Catagorized Notes
Renamed notes to fit categories and be easier to find later: blog, config, howto
2023-04-28 10:31:11 -04:00

124 lines
2.8 KiB
Markdown

# BASH Challenges
These are examples of scripting challenges I was given and helped create for interviewees
---
1. Check for the presence of a directory and create it if it doesn't exist
Example Solution
```bash
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
```bash
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
```bash
# 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
```bash
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.)
```bash
echo "1"; for x in {2..10}; do for i in {$x..2}; do echo -n $i,; done; echo -n "1"; echo ""; done
```
Best Solution:
```bash
for (( i=1;i<=10;i++ )); do eval printf -- '%d\\n' "{${i}..1}" | paste -sd ',' -;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
```
Tags:
howto