BASH Scripting Langauge

Unix shell and command language from the GNU project.

Scenarios

For-Each of something

Item in a list

for X in Item1 Item2 Item3 ; do echo $X ; done

Line in a file

while read -r LINE ; do printf "$LINE\n" ; done < some-text-file

Line in a string

while read -r LINE ; do printf "$LINE\n" ; done <<< "some\nstring"

Sub-directory

for D in `find . -type d` ; do printf "$D\n" ; done

Mechanics

Flags

set -e    # Halt execution if any command has non-zero exit
set -x    # Print/echo each command-line before execution

Directory of current file, regardless of how it was loaded

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

Operators

Comparison

 Field Type  Operator  Description
Integer -eq equal to
Integer -ne not equal to
Integer -gt greater than
Integer -ge greater or equal to
Integer -lt less than
Integer -le less or equal to
String == equal to
String != not equal to
String -z null (zero length)
String -n not null (+ length)
Compound -a logical AND
Compound -o logical OR

File Queries

 Operator  Description
-e file exists
-f is regular file
-s size greater than zero
-d is directory
-h is symbolic link
-r readable by current user
-w writable by current user
-x executable by current user
-O current user owns file
-G current user in file’s group
-nt f1 is newer than f2
-ot f1 is older than f2

Snippets

Converting space separated string into an array

IN="one two three"
AR=( $IN )
echo ${AR[0]}  # 'one'

Calculating age of file in seconds

THEN_TIME=$(stat -c %Z "${FILE}")
NOW_TIME=$(date +%s)
AGE_SEC=$(( ${NOW_TIME} - ${THEN_TIME} ))

Generating Random Passwords

Best to rely on OpenSSL for this if available, but other options are available depending on use-case.

$ openssl rand -base64 32
  1. Great writeup from How-To-Geek, 10 Ways to Generate a Random Password from the Command Line
  2. PDF backup of the article for the future