bash

References

Summary

It's similar to Windows Batch, in that it's built to string command-line expressions together.

Differences

Batch is based on MS-DOS

Bash is built on the POSIX standard

The downside of Bash is that if any commands update and change their output, scripts will easily break

Shebang

!# is called a shebang

#!/usr/bin/env bash

Even though bash is often just in /usr/bin/, coding in /usr/bin/etc tells the kernel to seach PATH, incase bash is somewhere else.

Errors

By default, if a line in a bash script fails, Bash will ignore it and keep going.

set -e: Tells bash to end if it encounters any errors (non-zero exit codes).

Commands

MODE="${1:-default}"

$1 represents the first positional argument passed to the script

$1:-default tells the program to evaluate variable one, and if it doesn't exist, to use the string 'default' for its default value

[ is a command alias for test

[ -d "$REPO" ] checks that the repo is a valid directory

$(command) is command substitution

git push origin main >> "LOG_FILE"

Bash first reroutes the output stream to LOG_FILE and then executes the command

git then writes its output to stdout as usual, but Bash has already pointed stdout to the log file.

File Descriptors

Every process of Linux gets automatically assigned 3 communication channels (file descriptors)

2>&1 means redirect file descriptor 2's stream to the current target of file descriptor 1

Variables

Bash reads local variables dynamically by default (unlike Batch)

Arrays

Unlike Batch, Bash actually has arrays natively

${REPOS[@]} tells Bash to unpack the entire array

Loops

Semicolons are syntactically equivalent to new lines.

Conditionals

if [ "$MODE" == "pull" ]; then
if ! git diff-index --quiet HEAD --; then

! is a logical inversion acting on git diff-index