Complete Script Template in Shell

Level 5261 keystrokes

A reusable script skeleton: strict mode, read-only paths computed from the script's own location, a log function that prints and appends to a log file, and a main function that receives all arguments. Timestamps vary.

Shell code

# Strict mode: stop on errors, unset variables and pipe failures
1set -euo pipefail
# Absolute directory of this script file (works from any working directory)
# readonly makes it a constant
2readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Log file next to the script, also read-only
3readonly LOG_FILE="$SCRIPT_DIR/script.log"
# log LEVEL MESSAGE: tee -a prints the line and appends it to the log file
4log() { echo "$(date '+%Y-%m-%d %H:%M:%S') [$1] $2" | tee -a "$LOG_FILE"; }
# main holds the script's logic
5main() {
6 log INFO "Starting"
7 log INFO "Done"
8}
# Call main with all command-line arguments
9main "$@"

Output

2024-01-15 14:30:45 [INFO] Starting
2024-01-15 14:30:45 [INFO] Done
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 18
  • $× 9
  • %× 6
  • _× 5
  • (× 5
  • )× 5
  • -× 4
  • {× 3
  • }× 3
  • :× 2

More Shell examples at level 5

← Shell typing practice