Skip to content

Instantly share code, notes, and snippets.

@idettman
Last active February 26, 2020 10:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idettman/3ef2541288be3f2b8a482d7c548c8666 to your computer and use it in GitHub Desktop.
Save idettman/3ef2541288be3f2b8a482d7c548c8666 to your computer and use it in GitHub Desktop.
cheatsheets
title keywords
Bash scripting
Variables
Functions
Interpolation
Brace expansions
Loops
Conditional execution
Command substitution

Getting started

{: .-three-column}

Example

#!/usr/bin/env bash

NAME="John"
echo "Hello $NAME!"

Variables

NAME="John"
echo $NAME
echo "$NAME"
echo "${NAME}!"

String quotes

NAME="John"
echo "Hi $NAME"  #=> Hi John
echo 'Hi $NAME'  #=> Hi $NAME

Shell execution

echo "I'm in $(pwd)"
echo "I'm in `pwd`"
# Same

See Command substitution

Conditional execution

git commit && git push
git commit || echo "Commit failed"

Functions

{: id='functions-example'}

get_name() {
  echo "John"
}

echo "You are $(get_name)"

See: Functions

Conditionals

{: id='conditionals-example'}

if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
fi

See: Conditionals

Strict mode

set -euo pipefail
IFS=$'\n\t'

See: Unofficial bash strict mode

Brace expansion

echo {A,B}.js

| {A,B} | Same as A B | | {A,B}.js | Same as A.js B.js | | {1..5} | Same as 1 2 3 4 5 |

See: Brace expansion

Parameter expansions

{: .-three-column}

Basics

name="John"
echo ${name}
echo ${name/J/j}    #=> "john" (substitution)
echo ${name:0:2}    #=> "Jo" (slicing)
echo ${name::2}     #=> "Jo" (slicing)
echo ${name::-1}    #=> "Joh" (slicing)
echo ${name:(-1)}   #=> "n" (slicing from right)
echo ${name:(-2):1} #=> "h" (slicing from right)
echo ${food:-Cake}  #=> $food or "Cake"
length=2
echo ${name:0:length}  #=> "Jo"

See: Parameter expansion

STR="/path/to/foo.cpp"
echo ${STR%.cpp}    # /path/to/foo
echo ${STR%.cpp}.o  # /path/to/foo.o

echo ${STR##*.}     # cpp (extension)
echo ${STR##*/}     # foo.cpp (basepath)

echo ${STR#*/}      # path/to/foo.cpp
echo ${STR##*/}     # foo.cpp

echo ${STR/foo/bar} # /path/to/bar.cpp
STR="Hello world"
echo ${STR:6:5}   # "world"
echo ${STR:-5:5}  # "world"
SRC="/path/to/foo.cpp"
BASE=${SRC##*/}   #=> "foo.cpp" (basepath)
DIR=${SRC%$BASE}  #=> "/path/to/" (dirpath)

Substitution

Code Description
${FOO%suffix} Remove suffix
${FOO#prefix} Remove prefix
--- ---
${FOO%%suffix} Remove long suffix
${FOO##prefix} Remove long prefix
--- ---
${FOO/from/to} Replace first match
${FOO//from/to} Replace all
--- ---
${FOO/%from/to} Replace suffix
${FOO/#from/to} Replace prefix

Comments

# Single line comment
: '
This is a
multi line
comment
'

Substrings

| ${FOO:0:3} | Substring (position, length) | | ${FOO:-3:3} | Substring from the right |

Length

| ${#FOO} | Length of $FOO |

Manipulation

STR="HELLO WORLD!"
echo ${STR,}   #=> "hELLO WORLD!" (lowercase 1st letter)
echo ${STR,,}  #=> "hello world!" (all lowercase)

STR="hello world!"
echo ${STR^}   #=> "Hello world!" (uppercase 1st letter)
echo ${STR^^}  #=> "HELLO WORLD!" (all uppercase)

Default values

| ${FOO:-val} | $FOO, or val if not set | | ${FOO:=val} | Set $FOO to val if not set | | ${FOO:+val} | val if $FOO is set | | ${FOO:?message} | Show error message and exit if $FOO is not set |

The : is optional (eg, ${FOO=word} works)

Loops

{: .-three-column}

Basic for loop

for i in /etc/rc.*; do
  echo $i
done

C-like for loop

for ((i = 0 ; i < 100 ; i++)); do
  echo $i
done

Ranges

for i in {1..5}; do
    echo "Welcome $i"
done

With step size

for i in {5..50..5}; do
    echo "Welcome $i"
done

Reading lines

cat file.txt | while read line; do
  echo $line
done

Forever

while true; do
  ···
done

Functions

{: .-three-column}

Defining functions

myfunc() {
    echo "hello $1"
}
# Same as above (alternate syntax)
function myfunc() {
    echo "hello $1"
}
myfunc "John"

Returning values

myfunc() {
    local myresult='some value'
    echo $myresult
}
result="$(myfunc)"

Raising errors

myfunc() {
  return 1
}
if myfunc; then
  echo "success"
else
  echo "failure"
fi

Arguments

Expression Description
$# Number of arguments
$* All arguments
$@ All arguments, starting from first
$1 First argument
$_ Last argument of the previous command

See Special parameters.

Conditionals

{: .-three-column}

Conditions

Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition, see examples.

Condition Description
[[ -z STRING ]] Empty string
[[ -n STRING ]] Not empty string
[[ STRING == STRING ]] Equal
[[ STRING != STRING ]] Not Equal
--- ---
[[ NUM -eq NUM ]] Equal
[[ NUM -ne NUM ]] Not equal
[[ NUM -lt NUM ]] Less than
[[ NUM -le NUM ]] Less than or equal
[[ NUM -gt NUM ]] Greater than
[[ NUM -ge NUM ]] Greater than or equal
--- ---
[[ STRING =~ STRING ]] Regexp
--- ---
(( NUM < NUM )) Numeric conditions
Condition Description
[[ -o noclobber ]] If OPTIONNAME is enabled
--- ---
[[ ! EXPR ]] Not
[[ X ]] && [[ Y ]] And
`[[ X ]]

File conditions

Condition Description
[[ -e FILE ]] Exists
[[ -r FILE ]] Readable
[[ -h FILE ]] Symlink
[[ -d FILE ]] Directory
[[ -w FILE ]] Writable
[[ -s FILE ]] Size is > 0 bytes
[[ -f FILE ]] File
[[ -x FILE ]] Executable
--- ---
[[ FILE1 -nt FILE2 ]] 1 is more recent than 2
[[ FILE1 -ot FILE2 ]] 2 is more recent than 1
[[ FILE1 -ef FILE2 ]] Same files

Example

# String
if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
fi
# Combinations
if [[ X ]] && [[ Y ]]; then
  ...
fi
# Equal
if [[ "$A" == "$B" ]]
# Regex
if [[ "A" =~ . ]]
if (( $a < $b )); then
   echo "$a is smaller than $b"
fi
if [[ -e "file.txt" ]]; then
  echo "file exists"
fi

Arrays

Defining arrays

Fruits=('Apple' 'Banana' 'Orange')
Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"

Working with arrays

echo ${Fruits[0]}           # Element #0
echo ${Fruits[@]}           # All elements, space-separated
echo ${#Fruits[@]}          # Number of elements
echo ${#Fruits}             # String length of the 1st element
echo ${#Fruits[3]}          # String length of the Nth element
echo ${Fruits[@]:3:2}       # Range (from position 3, length 2)

Operations

Fruits=("${Fruits[@]}" "Watermelon")    # Push
Fruits+=('Watermelon')                  # Also Push
Fruits=( ${Fruits[@]/Ap*/} )            # Remove by regex match
unset Fruits[2]                         # Remove one item
Fruits=("${Fruits[@]}")                 # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`)                 # Read from file

Iteration

for i in "${arrayName[@]}"; do
  echo $i
done

Dictionaries

{: .-three-column}

Defining

declare -A sounds
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"

Declares sound as a Dictionary object (aka associative array).

Working with dictionaries

echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]}   # All values
echo ${!sounds[@]}  # All keys
echo ${#sounds[@]}  # Number of elements
unset sounds[dog]   # Delete dog

Iteration

Iterate over values

for val in "${sounds[@]}"; do
  echo $val
done

Iterate over keys

for key in "${!sounds[@]}"; do
  echo $key
done

Options

Options

set -o noclobber  # Avoid overlay files (echo "hi" > foo)
set -o errexit    # Used to exit upon error, avoiding cascading errors
set -o pipefail   # Unveils hidden failures
set -o nounset    # Exposes unset variables

Glob options

shopt -s nullglob    # Non-matching globs are removed  ('*.foo' => '')
shopt -s failglob    # Non-matching globs throw errors
shopt -s nocaseglob  # Case insensitive globs
shopt -s dotglob     # Wildcards match dotfiles ("*.sh" => ".foo.sh")
shopt -s globstar    # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')

Set GLOBIGNORE as a colon-separated list of patterns to be removed from glob matches.

History

Commands

| history | Show history | | shopt -s histverify | Don't execute expanded result immediately |

Expansions

| !$ | Expand last parameter of most recent command | | !* | Expand all parameters of most recent command | | !-n | Expand nth most recent command | | !n | Expand nth command in history | | !<command> | Expand most recent invocation of command <command> |

Operations

| !! | Execute last command again |
| !!:s/<FROM>/<TO>/ | Replace first occurrence of <FROM> to <TO> in most recent command | | !!:gs/<FROM>/<TO>/ | Replace all occurrences of <FROM> to <TO> in most recent command | | !$:t | Expand only basename from last parameter of most recent command | | !$:h | Expand only directory from last parameter of most recent command |

!! and !$ can be replaced with any valid expansion.

Slices

| !!:n | Expand only nth token from most recent command (command is 0; first argument is 1) | | !^ | Expand first argument from most recent command | | !$ | Expand last token from most recent command | | !!:n-m | Expand range of tokens from most recent command | | !!:n-$ | Expand nth token to last from most recent command |

!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.

Miscellaneous

Numeric calculations

$((a + 200))      # Add 200 to $a
$((RANDOM%=200))  # Random number 0..200

Subshells

(cd somedir; echo "I'm now in $PWD")
pwd # still in first directory

Redirection

python hello.py > output.txt   # stdout to (file)
python hello.py >> output.txt  # stdout to (file), append
python hello.py 2> error.log   # stderr to (file)
python hello.py 2>&1           # stderr to stdout
python hello.py 2>/dev/null    # stderr to (null)
python hello.py &>/dev/null    # stdout and stderr to (null)
python hello.py < foo.txt      # feed foo.txt to stdin for python

Inspecting commands

command -V cd
#=> "cd is a function/alias/whatever"

Trap errors

trap 'echo Error at about $LINENO' ERR

or

traperr() {
  echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
}

set -o errtrace
trap traperr ERR

Case/switch

case "$1" in
  start | up)
    vagrant up
    ;;

  *)
    echo "Usage: $0 {start|stop|ssh}"
    ;;
esac

Source relative

source "${0%/*}/../share/foo.sh"

printf

printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga

printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"

printf "This is how you print a float: %f" 2
#=> "This is how you print a float: 2.000000"

Directory of script

DIR="${0%/*}"

Getting options

while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
  -V | --version )
    echo $version
    exit
    ;;
  -s | --string )
    shift; string=$1
    ;;
  -f | --flag )
    flag=1
    ;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi

Heredoc

cat <<END
hello world
END

Reading input

echo -n "Proceed? [y/n]: "
read ans
echo $ans
read -n 1 ans    # Just one character

Special variables

| $? | Exit status of last task | | $! | PID of last background task | | $$ | PID of shell | | $0 | Filename of the shell script |

See Special parameters.

Go to previous directory

pwd # /home/user/foo
cd bar/
pwd # /home/user/foo/bar
cd -
pwd # /home/user/foo

Check for command's result

if ping -c 1 google.com; then
  echo "It appears you have a working internet connection"
fi

Grep check

if grep -q 'foo' ~/.bash_history; then
  echo "You appear to have typed 'foo' in the past"
fi

Also see

{: .-one-column}

title
Curl

Options

Options

-o <file>    # --output: write to file
-u user:pass # --user: Authentication
-v           # --verbose
-vv          # Even more verbose
-s           # --silent
-i           # --include: Include the HTTP-header in the output
-I           # --head: headers only

Request

-X POST          # --request
-L               # follow link if page redirects 

Data

-d 'data'    # --data: HTTP post data, URL encoded (eg, status="Hello")
-d @file     # --data via file
-G           # --get: send -d data via get

Headers

-A <str>         # --user-agent
-b name=val      # --cookie
-b FILE          # --cookie
-H "X-Foo: y"    # --header
--compressed     # use deflate/gzip

SSL

    --cacert <file>
    --capath <dir>
-E, --cert <cert>     # --cert: Client cert file
    --cert-type       # der/pem/eng
-k, --insecure        # for self-signed certs

Examples

{: .-one-column}

# Post data:
curl -d password=x http://x.com/y
# Auth/data:
curl -u user:pass -d status="Hello" http://twitter.com/statuses/update.xml
# multipart file upload
curl -v -include --form key1=value1 --form upload=@localfilename URL
title
docker-compose

Basic example

# docker-compose.yml
version: '2'

services:
  web:
    build: .
    # build from Dockerfile
    context: ./Path
    dockerfile: Dockerfile
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  redis:
    image: redis

Commands

docker-compose start
docker-compose stop
docker-compose pause
docker-compose unpause
docker-compose ps
docker-compose up
docker-compose down

Reference

{: .-three-column}

Building

web:
  # build from Dockerfile
  build: .
  args:     # Add build arguments
    APP_HOME: app
  # build from custom Dockerfile
  build:
    context: ./dir
    dockerfile: Dockerfile.dev
  # build from image
  image: ubuntu
  image: ubuntu:14.04
  image: tutum/influxdb
  image: example-registry:4000/postgresql
  image: a4bc65fd

Ports

  ports:
    - "3000"
    - "8000:80"  # host:container
  # expose ports to linked services (not to host)
  expose: ["3000"]

Commands

  # command to execute
  command: bundle exec thin -p 3000
  command: [bundle, exec, thin, -p, 3000]
  # override the entrypoint
  entrypoint: /app/start.sh
  entrypoint: [php, -d, vendor/bin/phpunit]

Environment variables

  # environment vars
  environment:
    RACK_ENV: development
  environment:
    - RACK_ENV=development
  # environment vars from file
  env_file: .env
  env_file: [.env, .development.env]

Dependencies

  # makes the `db` service available as the hostname `database`
  # (implies depends_on)
  links:
    - db:database
    - redis
  # make sure `db` is alive before starting
  depends_on:
    - db

Other options

  # make this service extend another
  extends:
    file: common.yml  # optional
    service: webapp
  volumes:
    - /var/lib/mysql
    - ./_data:/var/lib/mysql

Advanced features

{: .-three-column}

Labels

services:
  web:
    labels:
      com.example.description: "Accounting web app"

DNS servers

services:
  web:
    dns: 8.8.8.8
    dns:
      - 8.8.8.8
      - 8.8.4.4

Devices

services:
  web:
    devices:
    - "/dev/ttyUSB0:/dev/ttyUSB0"

External links

services:
  web:
    external_links:
      - redis_1
      - project_db_1:mysql

Hosts

services:
  web:
    extra_hosts:
      - "somehost:192.168.1.100"

Network

# creates a custom network called `frontend`
networks:
  frontend:

External network

# join a pre-existing network
networks:
  default:
    external:
      name: frontend

Volume

# Mount host paths or named volumes, specified as sub-options to a service
  db:
    image: postgres:latest
    volumes:
      - "/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock"
      - "dbdata:/var/lib/postgresql/data"

volumes:
  dbdata:
title
Dockerfile

Reference

{: .-three-column}

Inheritance

FROM ruby:2.2.2

Variables

ENV APP_HOME /myapp
RUN mkdir $APP_HOME
ARG APP_HOME=""
RUN mkdir $APP_HOME

Initialization

RUN bundle install
WORKDIR /myapp
VOLUME ["/data"]
# Specification for mount point
ADD file.xyz /file.xyz
COPY --chown=user:group host_file.xyz /path/container_file.xyz

Onbuild

ONBUILD RUN bundle install
# when used with another file

Commands

EXPOSE 5900
CMD    ["bundle", "exec", "rails", "server"]

Entrypoint

ENTRYPOINT ["executable", "param1", "param2"]
ENTRYPOINT command param1 param2

Configures a container that will run as an executable.

ENTRYPOINT exec top -b

This will use shell processing to substitute shell variables, and will ignore any CMD or docker run command line arguments.

Metadata

LABEL version="1.0"
LABEL "com.example.vendor"="ACME Incorporated"
LABEL com.example.label-with-value="foo"
LABEL description="This text illustrates \
that label-values can span multiple lines."

See also

{: .-one-column}

title
editorconfig

Short example

{: .-prime}

# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
tab_width = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

This example should be fine for most projects indented by 2 spaces. See: animate.css editorconfig

Properties

indent_style = {space|tab}
indent_size = {4|tab}
tab_width = 2
end_of_line = {cr|lf|crlf}
charset = {utf-8|utf-16be|utf-16le|latin1}
trim_trailing_whitespace = false
insert_final_newline = true
max_line_length = 80

Full example

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# 4 space indentation
[*.py]
indent_style = space
indent_size = 4

# Tab indentation (no size specified)
[*.js]
indent_style = tab

# Indentation override for all JS under lib directory
[lib/**.js]
indent_style = space
indent_size = 2

# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2

References

title
ffmpeg

Common switches

-codecs          # list codecs
-c:v             # video codec (-vcodec) - 'copy' to copy stream
-c:a             # audio codec (-acodec)
-fs SIZE         # limit file size (bytes)

Bitrate

-b:v 1M          # video bitrate (1M = 1Mbit/s)
-b:a 1M          # audio bitrate

Video

-aspect RATIO    # aspect ratio (4:3, 16:9, or 1.25)
-r RATE          # frame rate per sec
-s WIDTHxHEIGHT  # frame size
-vn              # no video

Audio

-aq QUALITY      # audio quality (codec-specific)
-ar 44100        # audio sample rate (hz)
-ac 1            # audio channels (1=mono, 2=stereo)
-an              # no audio
-vol N           # volume (256=normal)

Example

Ringtone conversion using ffmpeg

ffmpeg -i foo.mp3 -ac 1 -ab 128000 -f mp4 -acodec libfaac -y target.m4r

To web

# no audio
ffmpeg -i input.mov -vcodec h264   -an -strict -2 output.mp4
ffmpeg -i input.mov -vcodec libvpx -an output.webm
ffmpeg -i input.mov -vcodec h264 -acodec aac -strict -2 output.mp4
ffmpeg -i input.mov -vcodec libvpx -acodec libvorbis output.webm
<video width="320" height="240" controls>
  <source src="movie.mp4" type='video/mp4'></source>
  <source src="movie.webm" type='video/ogg'></source>
</video>

tricks

Refs HEAD^ # 1 commit before head HEAD^^ # 2 commits before head HEAD~5 # 5 commits before head

Branches

create a new branch

git checkout -b $branchname git push origin $branchname --set-upstream

get a remote branch

git fetch origin git checkout --track origin/$branchname

delete local remote-tracking branches (lol)

git remote prune origin

list merged branches

git branch -a --merged

delete remote branch

git push origin :$branchname

go back to previous branch

git checkout -

Collaboration

Rebase your changes on top of the remote master

git pull --rebase upstream master

Squash multiple commits into one for a cleaner git log

(on the following screen change the word pick to either 'f' or 's')

git rebase -i $commit_ref

Submodules

Import .gitmodules

git submodule init

Clone missing submodules, and checkout commits

git submodule update --init --recursive

Update remote URLs in .gitmodules

(Use when you changed remotes in submodules)

git submodule sync Diff Diff with stats git diff --stat app/a.txt | 2 +- app/b.txt | 8 ++---- 2 files changed, 10 insertions(+), 84 deletions(-)

Just filenames

git diff --summary

Log options

--oneline e11e9f9 Commit message here

--decorate shows "(origin/master)"

--graph shows graph lines

--date=relative "2 hours ago"

Misc

Cherry pick git rebase 76acada^

Misc

get current sha1 (?)

git show-ref HEAD -s

show single commit info

git log -1 f5a960b5

Go back up to root directory

cd "$(git rev-parse --show-top-level)"

Short log

$ git shortlog $ git shortlog HEAD~20.. # last 20 commits

James Dean (1): Commit here Commit there

Frank Sinatra (5): Another commit This other commit

Bisect

git bisect start HEAD HEAD~6 git bisect run npm test git checkout refs/bisect/bad # this is where it screwed up git bisect reset

Manual bisection

git bisect start git bisect good # current version is good

git checkout HEAD~8 npm test # see if it's good git bisect bad # current version is bad

git bisect reset # abort

Searching

git log --grep="fixes things" # search in commit messages git log -S"window.alert" # search in code git log -G"foo.*" # search in code (regex)

GPG Signing

git config set user.signingkey # Sets GPG key to use for signing

git commit -m "Implement feature Y" --gpg-sign # Or -S, GPG signs commit

git config set commit.gpgsign true # Sign commits by default git commit -m "Implement feature Y" --no-gpg-sign # Do not sign

Working with branches

{: .-three-column}

Creating

git checkout -b $branchname
git push origin $branchname --set-upstream

Creates a new branch locally then pushes it.

Getting from remote

git fetch origin
git checkout --track origin/$branchname

Gets a branch in a remote.

Delete local remote-tracking branches

git remote prune origin

Deletes origin/* branches in your local copy. Doesn't affect the remote.

List existing branches

git branch --list

Existing branches are listed. Current branch will be highlighted with an asterisk.

List merged branches

git branch -a --merged

List outdated branches that have been merged into the current one.

Delete a local branch

git branch -d $branchname

Deletes the branch only if the changes have been pushed and merged with remote.

Delete branch forcefully

git branch -D $branchname
git branch -d $branchname

Note: You can also use the -D flag which is synonymous with --delete --force instead of -d. This will delete the branch regardless of its merge status. Delete a branch irrespective of its merged status.

Delete remote branch

git push origin --delete :$branchname

Works for tags, too!

Get current sha1

git show-ref HEAD -s

Reset branch and remove all changes

git reset --hard

Undo commits to a specific commit

git reset --hard $commit_id

# Now push to your branch
git push --force
title category
Homebrew
CLI

Commands

Command Description
brew install git Install a package
brew uninstall git Remove/Uninstall a package
brew upgrade git Upgrade a package
--- ---
brew unlink git Unlink
brew link git Link
brew switch git 2.5.0 Change versions
--- ---
brew list --versions git See what versions you have

More package commands

Command Description
brew info git List versions, caveats, etc
brew cleanup git Remove old versions
brew edit git Edit this formula
brew cat git Print this formula
brew home git Open homepage
brew search git Search for formulas

Global commands

Command Description
brew update Update brew and cask
brew list List installed
brew outdated What's due for upgrades?
brew doctor Diagnose brew issues

Brew Cask commands

Command Description
brew cask install firefox Install the Firefox browser
brew cask list List installed applications

Cask commands are used for interacting with graphical applications.

Also see

{: .-one-column}

title
Jsdoc

Functions

/**
 * This is a function.
 *
 * @param {string} n - A string param
 * @return {string} A good string
 *
 * @example
 *
 *     foo('hello')
 */

function foo(n) { return n }

See: http://usejsdoc.org/index.html

Types

Type Description
@param {string=} n Optional
@param {string} [n] Optional
`@param {(string number)} n`
@param {*} n Any type
@param {...string} n Repeatable arguments
@param {string} [n="hi"] Optional with default
@param {string[]} n Array of strings
@return {Promise<string[]>} n Promise fulfilled by array of strings

See: http://usejsdoc.org/tags-type.html

Variables

/**
 * @type {number}
 */
var FOO = 1
/**
 * @const {number}
 */
const FOO = 1

Typedef

/**
 * A song
 * @typedef {Object} Song
 * @property {string} title - The title
 * @property {string} artist - The artist
 * @property {number} year - The year
 */
/**
 * Plays a song
 * @param {Song} song - The {@link Song} to be played
 */

function play (song) {
}

See: http://usejsdoc.org/tags-typedef.html

Typedef Shorthand

/**
 * A song
 * @typedef {{title: string, artist: string, year: number}} Song
 */
/**
 * Plays a song
 * @param {Song} song - The {@link Song} to be played
 */

function play (song) {
}

See: http://usejsdoc.org/tags-typedef.html

Importing types

/**
 * @typedef {import('./Foo').default} Bar
 */

/**
 * @param {Bar} x
 */

function test(x) { }

This syntax is TypeScript-specific.

Other keywords

/**
 * @throws {FooException}
 * @private
 * @deprecated
 * @see
 *
 * @function
 * @class
 */

Renaming

/*
 * @alias Foo.bar
 * @name Foo.bar
 */

Prefer alias over name. See: http://usejsdoc.org/tags-alias.html

title
MySQL

Create / Open / Delete Database

CREATE DATABASE dbNameYouWant
CREATE DATABASE dbNameYouWant CHARACTER SET utf8
USE dbNameYouWant
DROP DATABASE dbNameYouWant
ALTER DATABASE dbNameYouWant CHARACTER SET utf8

Backup Database to SQL File

mysqldump -u Username -p dbNameYouWant > databasename_backup.sql

Restore from backup SQL File

mysql - u Username -p dbNameYouWant < databasename_backup.sql

Repair Tables After Unclean Shutdown

mysqlcheck --all-databases
mysqlcheck --all-databases --fast

Browsing

SHOW DATABASES
SHOW TABLES
SHOW FIELDS FROM table / DESCRIBE table
SHOW CREATE TABLE table
SHOW PROCESSLIST
KILL process_number

Select

SELECT * FROM table
SELECT * FROM table1, table2, ...
SELECT field1, field2, ... FROM table1, table2, ...
SELECT ... FROM ... WHERE condition
SELECT ... FROM ... WHERE condition GROUPBY field
SELECT ... FROM ... WHERE condition GROUPBY field HAVING condition2
SELECT ... FROM ... WHERE condition ORDER BY field1, field2
SELECT ... FROM ... WHERE condition ORDER BY field1, field2 DESC
SELECT ... FROM ... WHERE condition LIMIT 10
SELECT DISTINCT field1 FROM ...
SELECT DISTINCT field1, field2 FROM ...

Select - Join

SELECT ... FROM t1 JOIN t2 ON t1.id1 = t2.id2 WHERE condition
SELECT ... FROM t1 LEFT JOIN t2 ON t1.id1 = t2.id2 WHERE condition
SELECT ... FROM t1 JOIN (t2 JOIN t3 ON ...) ON ...

Conditions

field1 = value1
field1 <> value1
field1 LIKE 'value _ %'
field1 IS NULL
field1 IS NOT NULL
field1 IS IN (value1, value2)
field1 IS NOT IN (value1, value2)
condition1 AND condition2
condition1 OR condition2

Insert

INSERT INTO table1 (field1, field2, ...) VALUES (value1, value2, ...)

Delete

DELETE FROM table1 / TRUNCATE table1
DELETE FROM table1 WHERE condition
DELETE FROM table1, table2 FROM table1, table2 WHERE table1.id1 =
  table2.id2 AND condition

Update

UPDATE table1 SET field1=new_value1 WHERE condition
UPDATE table1, table2 SET field1=new_value1, field2=new_value2, ... WHERE
  table1.id1 = table2.id2 AND condition

Create / Delete / Modify Table

Create

CREATE TABLE table (field1 type1, field2 type2, ...)
CREATE TABLE table (field1 type1, field2 type2, ..., INDEX (field))
CREATE TABLE table (field1 type1, field2 type2, ..., PRIMARY KEY (field1))
CREATE TABLE table (field1 type1, field2 type2, ..., PRIMARY KEY (field1,
field2))
CREATE TABLE table1 (fk_field1 type1, field2 type2, ...,
  FOREIGN KEY (fk_field1) REFERENCES table2 (t2_fieldA))
    [ON UPDATE|ON DELETE] [CASCADE|SET NULL]
CREATE TABLE table1 (fk_field1 type1, fk_field2 type2, ...,
 FOREIGN KEY (fk_field1, fk_field2) REFERENCES table2 (t2_fieldA, t2_fieldB))
CREATE TABLE table IF NOT EXISTS (...)
CREATE TEMPORARY TABLE table (...)

Drop

DROP TABLE table
DROP TABLE IF EXISTS table
DROP TABLE table1, table2, ...

Alter

ALTER TABLE table MODIFY field1 type1
ALTER TABLE table MODIFY field1 type1 NOT NULL ...
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 NOT NULL ...
ALTER TABLE table ALTER field1 SET DEFAULT ...
ALTER TABLE table ALTER field1 DROP DEFAULT
ALTER TABLE table ADD new_name_field1 type1
ALTER TABLE table ADD new_name_field1 type1 FIRST
ALTER TABLE table ADD new_name_field1 type1 AFTER another_field
ALTER TABLE table DROP field1
ALTER TABLE table ADD INDEX (field);

Change field order

ALTER TABLE table MODIFY field1 type1 FIRST
ALTER TABLE table MODIFY field1 type1 AFTER another_field
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 FIRST
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 AFTER
  another_field

Keys

CREATE TABLE table (..., PRIMARY KEY (field1, field2))
CREATE TABLE table (..., FOREIGN KEY (field1, field2) REFERENCES table2
(t2_field1, t2_field2))

Users and Privileges

GRANT ALL PRIVILEGES ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT, INSERT, DELETE ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
REVOKE ALL PRIVILEGES ON base.* FROM 'user'@'host'; -- one permission only
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'host'; -- all permissions
SET PASSWORD = PASSWORD('new_pass')
SET PASSWORD FOR 'user'@'host' = PASSWORD('new_pass')
SET PASSWORD = OLD_PASSWORD('new_pass')
DROP USER 'user'@'host'

Host ‘%’ indicates any host.

Main Data Types

TINYINT (1o: -217+128)
SMALLINT (2o: +-65 000)
MEDIUMINT (3o: +-16 000 000)
INT (4o: +- 2 000 000 000)
BIGINT (8o: +-9.10^18)
Precise interval: -(2^(8*N-1)) -> (2^8*N)-1

⚠ INT(2) = "2 digits displayed" -- NOT "number with 2 digits max"

FLOAT(M,D)
DOUBLE(M,D)
FLOAT(D=0->53)

⚠ 8,3 -> 12345,678 -- NOT 12345678,123!

TIME (HH:MM)
YEAR (AAAA)
DATE (AAAA-MM-JJ)
DATETIME (AAAA-MM-JJ HH:MM; années 1000->9999)
TIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix)
VARCHAR (single-line; explicit size)
TEXT (multi-lines; max size=65535)
BLOB (binary; max size=65535)

Variants for TEXT&BLOB: TINY (max=255), MEDIUM (max=~16000), and LONG (max=4Go). Ex: VARCHAR(32), TINYTEXT, LONGBLOB, MEDIUMTEXT

ENUM ('value1', 'value2', ...) -- (default NULL, or '' if NOT NULL)

Reset Root Password

$ /etc/init.d/mysql stop
$ mysqld_safe --skip-grant-tables
$ mysql # on another terminal
mysql> UPDATE mysql.user SET password=PASSWORD('new_pass') WHERE user='root';
## Switch back to the mysqld_safe terminal and kill the process using Control + \
$ /etc/init.d/mysql start

SQL Join Example

SELECT * FROM order_items \
  LEFT OUTER JOIN orders \
  ON order_items.order_id = orders.id

{: .-wrap}

Joins are typically added to SELECT statements to add more columns and records.

Diagram

SELECT * FROM `A` INNER JOIN `B`

{: .-setup}

┌────────┐
│ A  ┌───┼────┐
│    │ ∩ │    │
└────┼───┘  B │
     └────────┘

{: .-box-chars.-setup}

Join What
Inner join
Left outer join A +
Right outer join + B
Full outer join A + + B
title description
regexp
Basic cheatsheets for regular expression

RegExp

{: .-three-column}

Character classes

Pattern Description
. Any character, except newline
\w Word
\d Digit
\s Whitespace
\W Not word
\D Not digit
\S Not whitespace
[abc] Any of a, b, or c
[a-e] Characters between a and e
[1-9] Digit between 1 and 9
[^abc] Any character except a, b or c

Anchors

Pattern Description
\G Start of match
^ Start of string
$ End of string
\A Start of string
\Z End of string
\z Absolute end of string
\b A word boundry
\B Non-word boundry
^abc Start with abc
abc$ End with abc

Escaped characters

Pattern Description
\. \* \\ Escape special character used by regex
\t Tab
\n Newline
\r Carriage return

Groups

Pattern Description
(abc) Capture group
`(a b)`
(?:abc) Match abc, but don't capture

Quantifiers

Pattern Description
a* Match 0 or more
a+ Match 1 or more
a? Match 0 or 1
a{5} Match exactly 5
a{,3} Match up to 3
a{3,} Match 3 or more
a{1,3} Match between 1 and 3

Lookahead & Lookbehind

Pattern Description
a(?=b) Match a in baby but not in bay
a(?!b) Match a in Stan but not in Stab
--- ---
(?<=a)b Match b in crabs but not in cribs
(?<!a)b Match b in fib but not in fab
title
Semver

Semver

Given a version number MAJOR.MINOR.PATCH: {: .-setup}

| MAJOR | incompatible API changes | | MINOR | add functionality (backwards-compatible) | | PATCH | bug fixes (backwards-compatible) |

Simple ranges

  1.2.3
 =1.2.3
 >1.2.3
 <1.2.3
>=1.2.3

Note that suffixed versions (1.2.3-rc1) are not matched.

Ranges

Range Description Notes
~1.2.3 is >=1.2.3 <1.3.0
--- --- ---
^1.2.3 is >=1.2.3 <2.0.0
^0.2.3 is >=0.2.3 <0.3.0 (0.x.x is special)
^0.0.1 is =0.0.1 (0.0.x is special)
--- --- ---
^1.2 is >=1.2.0 <2.0.0 (like ^1.2.0)
~1.2 is >=1.2.0 <1.3.0 (like ~1.2.0)
--- --- ---
^1 is >=1.0.0 <2.0.0
~1 same
1.x same
1.* same
1 same
--- --- ---
* any version
x same
{: .-shortcuts}

Hyphenated ranges

Range Description
1.2.3 - 2.3.4 is >=1.2.3 <=2.3.4

Partial right

Range Description
1.2.3 - 2.3 is >=1.2.3 <2.4.0
1.2.3 - 2 is >=1.2.3 <3.0.0

Partial left

Range Description
1.2 - 2.3.0 is 1.2.0 - 2.3.0

When the right is partial (eg, 2.3), missing pieces are assumed to be x (eg, 2.3.x).

When the left is partial (eg, 1.2), missing pieces are assumed to be 0 (eg, 1.2.0).

Combining ranges

Range Description
>=0.14 <16 And (space-separated)
`0.14.x

Pre-releases

1.2.3-prerelease+build

Explanation

| ^ | means "compatible with" | | ~ | means "reasonably close to" | | 0.x.x | is for "initial development" | | 1.x.x | means public API is defined | {: .-shortcuts}

References

{: .-one-column}

title intro
Vim
[Vim](http://www.vim.org/) is a very efficient text editor. This reference was made for Vim 8.0. For shortcut notation, see `:help key-notation`.

Getting started

{: .-three-column}

Exiting

{: .-prime}

Shortcut Description
:qa Close all files
:qa! Close all files, abandon changes
--- ---
:w Save
:wq / :x Save and close file
--- ---
:q Close file
:q! Close file, abandon changes
--- ---
ZZ Save and quit
ZQ Quit without checking changes
{: .-shortcuts}

Navigating

Shortcut Description
h j k l Arrow keys
<C-U> / <C-D> Page up/page down
{: .-shortcuts}

Words

| Shortcut | Description | ff| --- | --- | | b / w | Previous/next word | | ge / e | Previous/next end of word | {: .-shortcuts}

Line

Shortcut Description
0 (zero) Start of line
^ Start of line (after whitespace)
$ End of line
{: .-shortcuts}

Character

| fc | Go forward to character c | | Fc | Go backward to character c | {: .-shortcuts}

Document

Shortcut Description
gg First line
G Last line
:n Go to line n
nG Go to line n
{: .-shortcuts}

Window

Shortcut Description
zz Center this line
zt Top this line
H Move to top of screen
M Move to middle of screen
L Move to bottom of screen
{: .-shortcuts}

Tab pages

Shortcut Description
:tabedit [file] Edit file in a new tab
:tabfind [file] Open file if exists in new tab
:tabclose Close current tab
:tabs List all tabs
:tabfirst Go to first tab
:tablast Go to last tab
:tabn Go to next tab
:tabp Go to previous tab

Editing

Shortcut Description
a Append
i Insert
o Next line
O Previous line
--- ---
s Delete char and insert
S Delete line and insert
C Delete until end of line and insert
--- ---
r Replace one character
R Enter Replace mode
--- ---
u Undo changes
<C-R> Redo changes
{: .-shortcuts}

Exiting insert mode

Shortcut Description
Esc / <C-[> Exit insert mode
<C-C> Exit insert mode, and abort current command
{: .-shortcuts}

Clipboard

Shortcut Description
x Delete character
--- ---
dd Delete line (Cut)
yy Yank line (Copy)
--- ---
p Paste
P Paste before
{: .-shortcuts}

Visual mode

Shortcut Description
v Enter visual mode
V Enter visual line mode
<C-V> Enter visual block mode
{: .-shortcuts}

In visual mode

Shortcut Description
d / x Delete selection
s Replace selection
y Yank selection (Copy)
{: .-shortcuts}

See Operators for other things you can do.

Operators

{: .-three-column}

Usage

{: .-prime}

Operators let you operate in a range of text (defined by motion). These are performed in normal mode. {: .-setup}

| d | w | | Operator | Motion | {: .-css-breakdown}

Operators list

Shortcut Description
d Delete
y Yank (copy)
c Change (delete then insert)
--- ---
> Indent right
< Indent left
--- ---
g~ Swap case
gU Uppercase
gu Lowercase
--- ---
! Filter through external program
{: .-shortcuts}

See :help operator

Examples

Combine operators with motions to use them. {: .-setup}

Shortcut Description
dd (repeat the letter) Delete current line
dw Delete to next word
db Delete to beginning of word
2dd Delete 2 lines
dip Delete a text object (inside paragraph)
(in visual mode) d Delete selection

See: :help motion.txt

Text objects

{: .-three-column}

Usage

{: .-prime}

Text objects let you operate (with an operator) in or around text blocks (objects). {: .-setup}

| v | i | p | | Operator | [i]nside or [a]round | Text object | {: .-css-breakdown}

Text objects

Shortcut Description
p Paragraph
w Word
s Sentence
--- ---
[ ( { < A [], (), or {} block
' " ` A quoted string
--- ---
b A block [(
B A block in [{
t A XML tag block
{: .-shortcuts}

Examples

Shortcut Description
vip Select paragraph
vipipipip Select more
--- ---
yip Yank inner paragraph
yap Yank paragraph (including newline)
--- ---
dip Delete inner paragraph
cip Change inner paragraph
{: .-shortcuts}

See Operators for other things you can do.

Diff

Shortcut Description
gvimdiff file1 file2 [file3] See differencies between files, in HMI

Misc

Folds

Shortcut Description
zo / zO Open
zc / zC Close
za / zA Toggle
--- ---
zv Open folds for this line
--- ---
zM Close all
zR Open all
--- ---
zm Fold more (foldlevel += 1)
zr Fold less (foldlevel -= 1)
--- ---
zx Update folds
{: .-shortcuts}

Uppercase ones are recursive (eg, zO is open recursively).

Navigation

Shortcut Description
[( [{ [< Previous ( or { or <
]) Next
--- ---
[m Previous method start
[M Previous method end
{: .-shortcuts}

Jumping

Shortcut Description
<C-O> Go back to previous location
<C-I> Go forward
--- ---
gf Go to file in cursor
{: .-shortcuts}

Counters

Shortcut Description
<C-A> Increment number
<C-X> Decrement
{: .-shortcuts}

Windows

| z{height}<Cr> | Resize pane to {height} lines tall |

Tags

Shortcut Description
:tag Classname Jump to first definition of Classname
--- ---
<C-]> Jump to definition
g] See all definitions
<C-T> Go back to last tag
<C-O> <C-I> Back/forward
--- ---
:tselect Classname Find definitions of Classname
:tjump Classname Find definitions of Classname (auto-select 1st)
{: .-shortcuts}

Case

Shortcut Description
~ Toggle case (Case => cASE)
gU Uppercase
gu Lowercase
--- ---
gUU Uppercase current line (also gUgU)
guu Lowercase current line (also gugu)
{: .-shortcuts}

Do these in visual or normal mode.

Marks

Shortcut Description
`^ Last position of cursor in insert mode
`. Last change
`` Last jump
--- ---
ma Mark this cursor position as a
`a Jump to the cursor position a
'a Jump to the beginning of the line with position a
{: .-shortcuts}

Misc

Shortcut Description
. Repeat last command
]p Paste under the current indentation level
--- ---
:ff=unix Convert Windows line endings to Unix line endings
{: .-shortcuts}

Command line

Shortcut Description
<C-R><C-W> Insert current word into the command line
<C-R>" Paste from " register
<C-X><C-F> Auto-completion of path in insert mode
{: .-shortcuts}

Text alignment

:center [width]
:right [width]
:left

See :help formatting

Calculator

Shortcut Description
<C-R>=128/2 Shows the result of the division : '64'

Do this in insert mode.

Exiting with an error

:cq
:cquit

Works like :qa, but throws an error. Great for aborting Git commands.

Spell checking

Shortcut Description
:set spell spelllang=en_us Turn on US English spell checking
]s Move to next misspelled word after the cursor
[s Move to previous misspelled word before the cursor
z= Suggest spellings for the word under/after the cursor
zg Add word to spell list
zw Mark word as bad/mispelling
zu / C-X (Insert Mode) Suggest words for bad word under cursor from spellfile
{: .-shortcuts}

See :help spell

Also see

title
zsh

Expressions

Expression Example Description
!! sudo !! Last command (sudo !!)
--- --- ---
!* vim !* Last command's parameters (vim !*)
!^ Last command's first parameter
!$ Last command's last parameter
--- --- ---
!?ls <tab> sudo !?mv <tab> Command and params of last ls command
!?ls?:* <tab> Params of last ls command
--- --- ---
*(m0) rm *(m0) Last modified today
*(m-4) Last modified <4 days ago
{: .-headers}

Change default shell

chsh -s `which zsh`

Process Substitution

Expression Example Description
<(COMMAND) grep "needle" <(curl "https://haystack.io") Replace argument with named pipe/FIFO (read-only) with command output
=(COMMAND) vim =(curl "https://haystack.io") Replace argument with file (writable) containing command output
{: .-headers}

Also see

Zsh is mostly compatible with Bash, so most everything in Bash's cheatsheet also applies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment