Introduction

Scripting vs Programming?

There’s no real distinction between “scripting” and “programming but generally…”

Pithy

Scripting is the use of software as a kind of universal glue that binds various commands, libraries and configuration files into a more functional whole.

Scripting philosophies

Tip

Write small scripts - you achieve most efficiencies by saving a few keystrokes here and a few commands there As a general rule, approach every chore with the question, “How can I avoid having to deal with this issue again in the future?”
Keep small scripts in ~/bin

$PATH Variable

$PATH is just a convention like any other

  • It’s an environment variable
  • It tells your shell where to check when you call for a executable (binary or script)
  • It searches in order, picking the first executable that matches
# Format:
# It's a list of folders seperate by colons
echo $PATH | column -t -s :
/home/mat/.cargo/bin  /usr/local/sbin  /usr/local/bin  /usr/sbin  /usr/bin  /sbin  /bin  /usr/games  /usr/local/games  /snap/bin

# Config (RC = run commands)
export PATH="$HOME/bin:$HOME/.local/bin:/usr/local/bin:$PATH"
/home/mat/bin
home/mat/.local/bin
/usr/local/bin
$PATH  # This is a must because your shell inherits the env vars from your parent process.
# This variable will add it your new list of paths
# Some of these are added at login time using the ~/.profile script

Exported variables

When you run:

export HELLO="world"

The shell does the following

  1. looks up up HELLO
  2. adds it if doesn’t exist
  3. sets the value to world
  4. sets the boolean flag exported
# Table of shell variables
Name    Value    Exported
----    -----    --------
HELLO   world    yes        # envrionment variable (passed to child)
PS1     ...      no         # shell variable (not passed down)

An exported variable just means it will be passed into the child shell.
So if you export a variable and run a script that reads environment variables only exported variables will be passed in.

Variables and quoting

Omit spaces around the = symbol; otherwise, the shell mistakes your variable name for a command name and treats the rest of the line as a series of arguments to that command.

etcdir='/etc'
echo $etcdir
# single quotes = string literals, no variable expansion
echo '$HOME' # = $HOME
# double quotes will expand variables
echo "$HOME" # = /home/mat

Curly braces when referencing a variable

You can surround its name with curly braces to clarify to the parser and to human readers where the variable name stops and other text begins

The braces are not normally required, but they can be useful when you want to expand variables inside double-quoted strings. Often, you’ll want the contents of a variable to be followed by literal letters or punctuation.

${etcdir}   # instead of $etcdir
echo "${file}s"        # without braces, shell reads $files (wrong variable)
echo "${name^}"        # capitalize first letter