Skip to content

Instantly share code, notes, and snippets.

@mwinters0
Last active January 15, 2026 04:55
Show Gist options
  • Select an option

  • Save mwinters0/b5496dee24d7e9bc0812dfee4951e0a1 to your computer and use it in GitHub Desktop.

Select an option

Save mwinters0/b5496dee24d7e9bc0812dfee4951e0a1 to your computer and use it in GitHub Desktop.
my bash cheat sheet

Bash cheat sheet

Only the most common stuff

Script dir

# Doesn't work if "this file" is a symlink
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd )
# Doesn't work if you're trying to "source" this script
SCRIPT_DIR=$(dirname -- "$(readlink -f -- "$0";)";)
# Works everywhere, but since this does `cd` out you may not be able to `cd` back in
pushd . > '/dev/null';
SCRIPT_PATH="${BASH_SOURCE[0]:-$0}";
while [ -h "$SCRIPT_PATH" ];
do
    cd "$(dirname -- "$SCRIPT_PATH")";
    SCRIPT_PATH="$(readlink -f -- "$SCRIPT_PATH")";
done
cd "$(dirname -- "$SCRIPT_PATH")" > '/dev/null';
SCRIPT_PATH="$(pwd)";
popd > '/dev/null';

Required / default vars

: "${REQVAR:?You must set REQVAR}"
: "${MAYBEVAR:='default value'}"

Pass all arguments

#!/bin/bash
otherprog "$@"   # equvalent to "$1" "$2" ...
otherprog $*     # same thing
otherprog "$*"   # equivalent to "$1 $2" 

All but the first:

#!/bin/bash
shift
otherprog "$@"   # equvalent to "$2" "$3" ...

Arrays

Declare

my_arr=(foo bar baz)
my_arr+=(bing boom)    #append
arr_size=${#my_arr[@]} #count

Iterate

# By value
for v in "${my_arr[@]}"; do
    echo $v
done
# By index
for i in "${!my_arr[@]}"; do
  echo ${my_arr[$i]}
done

Delete matching (only first match)

# delete the 'foo' element from my_arr
my_arr=( "${my_arr[@]/foo}" )

or

delete='foo'
my_arr=( "${my_arr[@]/$delete}" )

Pass to function

You can't. You have two options:

  1. Treat it like a vararg, passing the expanded version:
    function foo () {
        local bar="$1"
        shift
        local baz="$1"
        shift
        local rest=("$@")
    }
    
    neet=(bing bang boom)
    foo "bar" "baz" "${neet[@]}"
  2. Pass it as a nameref:
    function foo () {
        local bar="$1"
        local baz="$2"
        local -n rest="$3"
    }
    
    neet=(bing bang boom)
    foo "bar" "baz" "neet"

Strings

trim whitespace

FOO=$(echo "$FOO" | xargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment