Marks Notes

bash

A UNIX shell that is mostly POSIX compliant

Shellcheck

Use shellcheck to check for errors in a bash script. It can be integrated with Neovim

shellcheck script.sh

Variables

Set a variable

Pay attention to the spacing between the variable name and definition. There should be no space!

var=value

Use a variable

Case-sensitive. Environment variables should be all caps by convention. There are no numbers, only strings. Always use quotes around variables

cat "$filename"

You can add additional things to the string similar to how f-strings-python are done.

cat "{$filename}2"

Environment variables

Print env variables

env

Set environment variables

export MY_AWESOME_ENVIRONMENT_VAR=awesome

The reason why defining things in .bashrc makes them persistent across shells is that children inherent parent processes’ environment variables, and .bashrc runs first.

Arguments

Arguments are zero-indexed. To get an argument from within the script use “$0” “$1” etc.

note Note Remember, always quote your variables!

You can get all arguments through "$@". For example, to loop over all arguments

for i in "$@"
do
echo "Look mom no hands!"
done

Alias

Allows you to rename a command to something else. For example, you could alias eza to ls

alias ls="eza"

Brackets

() runs things in a subshell

(echo "This is in a subshell")

$(()) does arithmetic

x=(1 2 3) creates an array

if [[condition]] (double brackets are bash syntax, not POSIX)

Conditions

0 is the successful exit status. Any other number represents failure.

if COMMAND; then
  # code to run
fi

Combine statements with && for AND and || for OR.

Loops

for i in swamp man
do
   echo "$i"
done

Loop over files

for i in *.jpg
do
  convert "$i"
done

While loops

while COMMAND
do 
 ...
done

Loop over range of numbers

for i in $(seq 1 5)

Functions

test_function() {
  echo "test"
}

Call the function without brackets

test_function

note Note You cannot return a string, only exit codes.

Pipes

Use | to send the output of one process to the input of another

Background processes

Use the & sign at the end of a line to run a process in the background. You can keep a background process running when the terminal is closed with nohup

nohup ./command &