Command Line Cheat Sheet for GNU/Linux and macOS

Being effective on the command line can save a lot of time through daily developer activities. The command line on Unix-like systems like macOS and GNU/Linux use a so called shell. There are different shell implementations. From Unix days there are the Bourne Shell (bsh), the Korn Shell (ksh), the C Shell (csh) and so on. A free implementation of the Bourne Shell is the GNU Bourne Again Shell (bash), which is the most used shell these days. Most GNU/Linux systems as well as macOS use it. Depending on the system you may also encounter other types of shells like the Almqvist Shell (ash) on Alpine Linux, which is popular for Docker containers.

Shell short-cuts

Below is a list of short-cuts that come handy when using a shell.

Short-cut Description
Ctrl + A Move to the beginning of the command line (of course also Home)
Ctrl + E Move to the end of the command line (of course also End)
Ctrl + R Search the command history (Esc leaves the search mode)
Ctrl + U Delete everything before the cursor position
Arrow Up Move back in the command history
Arrow Down Move forward in the command history
Tab Auto-complete paths, Git Branches, Docker container/image names, ...
Ctrl + C interrupt the currently running process (it receives SIGINT)
Ctrl + Z stops the currently running process (it receives SIGTSTP), it can be resumed by fg in the foreground or bg in the background
Ctrl + \ terminates the currently running process and causes it to dump core (it receives SIGQUIT)
Ctrl + D is the sequence for the EOF (end of file) special control character
it closes the input stream of the shell and thus closes the shell itself

Shell variables

Shell variables are used to set information (paths, program names) that should be globally available or should not or cannot passed via parameters.

Command Explanation
export VAR=VAL Sets the variable VAR to the value VAL. The variable is only defined as long the current session remains.
export VAR=ls -l As above, but you can use back-ticks to assign the output of a command to a variable.
$VAR Accesses the content of the variable VAR.
"${foo}bar" Variables are automatically expanded within double quotes. To let the interpreter know where a variable starts and ends you can use curly braces.

There are some special shell variables which are listed below. Which variables are available depends on the type of shell.

Variable Comment
? Captures the exit code of the last run command.
PATH Contains directory paths separated by colon :, which tell the interpreter in which places to search for commands.
EDITOR The default editor that is invoked by a script or program.
HOME Contains the home directory of the current user.
IFS This internal field separator determines how the shell recognizes fields when parsing text.
PAGER The default filter program when a program outputs a lot of text to the terminal.
PWD This is the current working directory.

By default defined shell variables are only valid for the current session. To ensure a specific variable is set during start of a session (e.g. PATH) they can be defined in special files depending on the type of shell used (here: bash).

File Comment
/etc/profile All settings that should be applied to all your users.
/etc/bashrc If you have also other shells it might be better to put bash specific commands in this file as /etc/profile is also be read by other shells.
~/.bash_profile or ~/.profile User specific settings for login shells. .profile is also read by other shells.
~/.bashrc User specific settings for non-login shells.

Input and output

Like other programs shells use the three standard communication channels standard input (stdin), standard output (stdout) and standard error (stderr). Those channels can be redirected through pipes. For example output of a program to stdout can be written to a file. The symbol for a pipe on the shell is (|, > or <) also signalling the direction of the pipe. The vertical bar denotes a pipeline of stdout to stdin.

Command Explanation
ls -l | less Output of ls is directly fed into less thus producing a paged output of the directory listing.
ls -l > listing.txt Output of ls (on stdout) is piped into the file listing.txt (stderr is unaffected)
mysql -u root db < file.sql Content of file.sql is imported into the MySQL database db
composer 2> error.txt Error output of composer (on stderr) is piped into the file error.txt (stdout is unaffected)
composer > output.txt 2>&1 Output of stderr is re-routed to stdout and as stdout is piped into the file output.txt both stdout and stderr end up in this file

Not directly related but also useful is the possibility of chaining commands together via the semicolon ;. This involves no piping and also no conditional execution as below. The chained commands are simply executed in order. Example: ls -l; cat test.txt

Exit code and conditional execution

Each process can pass a value to the parent process while terminating. This value is called exit code or exit status. The standard convention is for the program to pass 0 for successful executions and 1 or higher for failed executions. In the shell the exit code is typically made available via the variable $?, which is only valid immediately after the command it refers to. In bash list constructs using && and || make use of the exit code as in the following examples:

Command Explanation
foo && bar executes foo and if its exit code is 0 also executes bar
foo || bar executes foo and if its exit code is > 0 also executes bar
foo && bar || foobar executes foo and if its exit code is 0 executes bar, if its exit code is > 0 executes foobar

Cron

Cron enables you to run scheduled commands at specified times and at specified intervals. Every user has a file called crontab which contains the commands, programs or scripts (tasks) that should be executed by cron. Each task is written on a separate line. A crontab line could look like the following:

45 23 * * 6 /home/user/scripts/export.sh

This executes /home/user/scripts/export.sh at 23:45 every Saturday. The fields are (from left to right):

  • minute (0 - 59)
  • hour (0 - 23)
  • day of month (1 - 31)
  • month (1 - 12)
  • day of week (0 - 6) (Sunday to Saturday; 7 is also Sunday on some systems)
  • command

Commands to manage the crontab are:

Command Explanation
crontab -l Display the content of the crontab of the current user
crontab -e Edit the content of the crontab of the current user with the default editor.
crontab -u USER Display or edit the content of the crontab of the user USER. You must be root to be allowed to do that.

One thing to be aware of are user permissions when running cron. Often daemons drop privileges so they don't run as root and the often don't run as your normal user either. If you have to read and write files managed by those daemons you should run the cron job as the daemon user. To e.g. modify the crontab of www-data (the webserver user on some systems) you would execute crontab -u www-data -e. Also, when you run cron as your normal user environment variables might not be set the way you are used to. The reason for that is that cron runs in a different environment than your normal login shell. Especially PATH sometimes differs. One rule of thumb to avoid problems therefore is to use absolute paths whenever possible when using cron.

Process management

In Unix-like systems processes receive a process id (PID). The process with PID 1 is the init process, which is responsible of starting and terminating all the other processes and perform clean-up. Processes can spawn child processes, they can run in foreground or in background (daemonized) as daemons.

Signals

Processes communicate via signals. Important signals are:

Name Description
SIGHUP Is send to a process if its controlling terminal is closed, it may then terminate or perform an other action (daemons often reload and switch to log files).
SIGINT Is send to a process when the user wants to interrupt the process.
SIGKILL Is send to a process if it should terminate immediately.
SIGQUIT Is send to a process when the user wants it to quit and dump core.
SIGSEGV Is send to a process when it references an invalid area in memory (segmentation fault)
SIGTERM Is send to a process if it should terminate. Unlike SIGKILL this allows for orderly termination.
SIGTSTP Is send to a process when the users wants it to stop.

Managing processes in general

Command Explanation
top displays interactive information about running processes and about resource consumption on the system (e.g. amount of RAM and swap, CPU load, general system load etc.)
quit by hitting Esc
use E (capital e) to cycle through different units for RAM consumption (default is the quite unreadable unit bytes)
ps -Af shows a snapshot of all running process with extended listing
kill PID sends SIGTERM to the process with the id PID (it can terminate in an orderly fashion or also ignore it)
kill -KILL PID sends SIGKILL to the process with the id PID causing it to terminate immediately
killall NAME sends SIGTERM to all processes with name NAME
killall -KILL NAME sends SIGKILL to all processes with name NAME causing them to terminate immediately
bg [jobID] resumes a suspended (e.g. with Ctrl + Z) job (with job id jobID) and keeps it running in the background
fg [jobID] resumes a suspended (e.g. with Ctrl + Z) job (with job id jobID) and keeps it running in the foreground (interactively)
jobs lists the status of all running jobs
disown [jobID] removes the job (with id jobID) from the job list, stdin/stdout are still connected to the terminal, will not receive SIGHUP from the shell
nohup disconnects stdin/stdout of the job (with id jobID) from the terminal, redirects output to nohup.out, will not receive SIGHUP from the shell, does not remove the job from the job list
%n or %% resume/bring to foreground the job with number n (as listed with jobs) or resume/bring to foreground the current job (marked with + in jobs)

jobID is either %n with n being the number that is listed with jobs or %% for the current job (that is marked with + in jobs).

Process vs. job: A job refers to a process or a group of processes. E.g. grep foo file.txt | less is a process group that consists of the processes grep and less. Process groups are managed by the shell as a whole - as a job.

Managing daemons

In the case of daemons (programs running in background) there are commands in place that enable to start them on system startup, start and stop them. Those commands depend largely on the init system that is used by the system. On Linux systems e.g. systemd (e.g. Ubuntu 16.04 LTS, CentOS 7) and upstart (Ubuntu 14.04 LTS, CentOS 6) play an important role.

upstart

Note that not all daemons may implement every command listed below. Those commands generally need to be run as root.

Command Explanation
service NAME status Display the status of the daemon with the name NAME (e.g. if it is running).
service NAME start Start the daemon with the name NAME if it is not running.
service NAME stop Stop (terminate in a orderly fashion) the daemon with the name NAME if it is running.
service NAME restart Restart the daemon with the name NAME, starts it if it is not running.
service NAME reload Reload configuration files of the daemon with name NAME, often without restarting the daemon itself (no service interruption).

systemd

Note that not all daemons may implement every command listed below. Those commands generally need to be run as root.

Command Explanation
systemctl status NAME Display the status of the daemon with the name NAME (e.g. if it is running).
systemctl start NAME Start the daemon with the name NAME if it is not running.
systemctl stop NAME Stop (terminate in a orderly fashion) the daemon with the name NAME if it is running.
systemctl restart NAME Restart the daemon with the name NAME, starts it if it is not running.
systemctl reload NAME Reload configuration files of the daemon with name NAME, often without restarting the daemon itself (no service interruption).
journalctl Queries the contents of the systemd journal
journalctl -xe Shows the end of the systemd journal including some helping information.

Resource management

Command Explanation
df -h output file system usage in human readable format
free -m output RAM usage
ncdu analyse file system usage (where are the largest directories/files?)
top displays interactive information about running processes and resource consumption
ip addr show [IFACE] displays information about network interfaces without IFACE parameter and about a specific interface with IFACE parameter (Linux only, old: ifconfig)
ip link set IFACE up/down activates/deactivates the specified network interface (Linux only, old: ifconfig)
ss -tulpen displays information about listening tcp and udp sockets with extended information (Linux only, old: netstat)
ifconfig [IFACE] displays information about network interfaces without IFACE parameter and about a specific interface with IFACE parameter (old version of ip addr show)
ifconfig IFACE up/down activates/deactivates the specified network interface (old version of ip link set)
netstat -tulpen displays information about listening tcp and udp sockets with extended information

File and directory management

Paths

First a word about paths: The directory separator in unix-like systems is the slash /. The file system root is the single slash /, dot . and double dot .. denote the current and parent directory respectively. On GNU/Linux systems user folders are typically located under /home/user and root (the system administrator) resides under /root. On macOS user folders are found in /Users/user. The short-cut for the folder of the current user is the tilde ~, which can be used in paths.

Permissions

A file or directory can belong to a user (the owner) and a group. Unix-style file permissions are threefold with some extra flags. The three categories are: owner, group (affects the user if s/he belongs to this group) and others (not the owner and not belonging to the group of the file). The basic file operations for permissions are read r, write w and execute x. Permissions can be either represented through characters e.g. rw------- (the owner can read and write, all others have no access) or through octal notation e.g. 600 (the same as before).

Hidden files

On Unix-like systems hidden files start with a dot . e.g. .htaccess. These files are not normally displayed, but are otherwise normal files. macOS places special restrictions on those files in the GUI, not only on displaying, but also on renaming and deleting them.

The data structure of a file-system on Unix-like systems consists of inodes. A file name is basically a pointer/name towards a inode. These names can be linked. A hard link references the inode directly, therefore it is another name for a inode. That means that if you change the original file name the hard link remains unaffected.

In contrast a symbolic link references the file name of a file. If you change the original file name the symbolic link will become broken.

Command Explanation
cd DIR change the current working directory to the specified directory, e.g. cd ~ to the current users directory, or cd .. to the parent directory
ls PATTERN list the contents of the current directory, PATTERN specifies a glob pattern, e.g. ls *.txt, if no pattern is specified all files are listed
ls -l (or ll) list the contents of the current directory with list formatting and more information (like file permissions) on some systems you can use the short form ll for ls -l.
ls -a / ls -al list the contents of the current directory including hidden files (dot-files)
mkdir PATH creates a directory with the given path
touch PATH creates a empty file with the given path
rm PATH removes the file with the given path (asks for permission again), files are not moved to some kind of trash first, but deleted immediately
rm -f PATH forces removal of the file with the given path (does not ask for permission again)
rm -r PATH recursively deletes the directory with the given path, otherwise rm refuses to delete non-empty directories
rm -rf PATH recursively force deletes the directory with the given path
cp FROM TO copies files from the given location to another, refuses to copy directories
cp -r FROM TO recursively copies directories from the given location to another
mv FROM TO renames files/directory from one location to another (means they can be also moved), no recursive flag is necessary here
ln -s TARGET NAME creates a symbolic link to TARGET with the name NAME
chown user PATH changes the owner of a file/directory.
Only root is able to do that.
chown -R user PATH changes the owner recursively (for all sub-directories and files) for the specified directory
chgrp group PATH changes the group of a file/directory.
Only root is able to do that.
chgrp -R group PATH changes the group recursively (for all sub-directories and files) for the specified directory
chown user:group PATH changes the owner and group of a file/directory to the specified values.
chmod PERMISSIONS PATH changes the permissions of the specified PATH to PERMISSIONS
chmod -R PERMISSIONS PATH changes the permissions recursively (for all sub-directories and files) of the specified PATH to PERMISSIONS

PERMISSIONS can be: an octal representation like 600 or 0600 where the numbers stand for combinations of r, w, and x a character representation of r, w, and x - u stands for user, g for group and o for others (not owner!), a stands for all users - + represents the addition of a permission while - represents the removal of a permission - = represents the setting of the referenced permissions

Examples:

  • ugo+x gives execute rights to user, group and others, equivalent with a+x
  • u+rw,go-w adds read and write rights to the owner and removes write rights for group and others
  • u=rw,go=r sets permissions to read and write for owner and to read for all other users

Especially for text files the following commands are helpful:

Command Explanation
cat FILE print the content of a file to standard output
less FILE comfortable pager for text files, useful if no editing capability is required
more FILE pager for text files (see above)
head FILE outputs the beginning of a file
head -n NR FILE outputs the first NR lines of a file
tail FILE outputs the end of a file
tail -f FILE continuously outputs the last lines of a file, exit the program with Ctrl + C
tail -n NR FILE outputs the last NR lines of a file

Text editors

There are quite a few text editors like vim, nano or emacs available. Which one is used is very much dependent on personal preference.

nano

Command Explanation
Ctrl + A / Home Move to the beginning of a line
Ctrl + E / End Move to the end of a line
Arrow Keys Move around in the text
Pg Up (macOS?) Move a page up
Pg Down (macOS?) Move a page down
Ctrl + O Save
Ctrl + X Exit
Ctrl + W Search
Ctrl + K Remove (cut) entire line

vim

vim has different modes e.g. the normal mode and the insert mode. In insert mode you input text. Normal mode offers a wide variety of keys to enter commands. More complex commands can be input by pressing colon :.

Command Explanation
Ins / I Enter insert mode
Esc Leave insert mode
Ctrl + A / Home Move to the beginning of a line
Ctrl + E / End Move to the end of a line
Arrow Keys Move around in the text
Pg Up (macOS?) Move a page up
Pg Down (macOS?) Move a page down
:q Exit without saving (normal mode)
:q! Exit without saving despite changes (normal mode)
:w Save (normal mode)
D Delete line (normal mode)

Software and package managers

Package managers are a very convenient way to install, update and manage software. On systems that offer a package manager it should be avoided to install software manually as this makes it difficult to update, replace or uninstall the software. Sometimes required software is not available in the official package repositories or only in an outdated version. This is especially the case on systems with long-term support such as Debian, Ubuntu LTS, CentOS or RHEL. Often there is the possibility to install third-party package source to get the required software. This should be the preferred option instead of manual installation. Never compile a software from source on a production server, as this requires a lot of additional software which increases the attack surface. Instead setup a bulid system with the same architecture, compile the software there and move it to the production system.

On GNU/Linux systems today basically two package managing worlds exist: the Debian package world with apt-get and dpkg and the Red Hat package world with yum and rpm. Another popular because lightweight alternative in the Docker world is Alpine Linux with its package manager apk.

apt-get

Command Explanation
apt-get update Updates package sources
apt-get install PKG Installs the specified package PKG including dependencies. A summary is displayed which has to be acknowledged.
apt-get install -y PKG As above, but avoids the acknowledgement of the summary
apt-get remove PKG Removes the specified package. This leaves dependencies and configuration files installed.
apt-get purge PKG Removes the specified package including configuration files. Leaves dependencies installed.
apt-get autoremove Removes orphaned packages e.g. dependencies that are no longer needed
apt-get upgrade Installs package updates
add-apt-repository ppa:NAME Installs the package source NAME. PPAs (personal package archives) are a special form of package source of Ubuntu.
add-apt-repository DEB_LINE Alternatively a package source can also be installed by providing the deb line e.g. deb http://packages.linuxmint.com/ julia main

yum

Command Explanation
yum install PKG Installs the specified package PKG including dependencies. A summary is displayed which has to be acknowledged.
yum -y install PKG As above, but avoids the acknowledgement of the summary
yum remove PKG Removes the specified package. This also removes unused dependencies and may remove configuration files.
yum check-update Checks for available package updates
yum update Installs package updates
yum update PKG Update a specific package

SSH and SCP

With SSH you can securely connect to remote servers and with scp you can copy files back and forth. When using SSH traffic is end-to-end encrypted. To prevent man-in-the-middle attacks SSH uses a key to identify the servers. For authentication either passwords or public keys can be used with public keys being the recommended alternative. The user specific files for authentication are managed in the .ssh directory in the user home directory (e.g. /Users/you/.ssh on macOS or /root/.ssh or /home/you/.ssh on GNU/Linux machines). Here is a overview over the files:

File Usage
known_hosts The system stores the known server keys in this file.
authorized_keys The system stores the public keys that are authorized to login as this user without password.
id_rsa This is the private key of the user, which is used for authentication. It must not be readable by group or others i.e. rw------- (600)
id_rsa.pub This is the public key of the users, which has to be entered in authorized_keys on other machines

Generating keys and key management

Command Explanation
ssh-keygen -t rsa -b 4096 -C EMAIL This generates a 4096 bit long RSA key and prompts you for a password (empty for none). It uses your e-mail address as a comment to identify the key.
It is strongly advisable to not store a private key unencrypted on disk.
ssh-keygen -t ed25519 -C EMAIL This generates a Ed25519 key based on elliptic curves and prompts you for a password (empty for none). This method is considered as or more secure than RSA and the key is much shorter. When supported this should be preferred over RSA.
It is strongly advisable to not store a private key unencrypted on disk.
ssh-keygen -f ~/.ssh/id_rsa -t ed25519 -C EMAIL as above but lets you specify the file name and location of the key
ssh-copy-id -i ~/.ssh/id_rsa user@host This adds your identity (public key) to a server provided that you also have password access to that server
ssh-add -l List all identities currently managed by ssh-agent
ssh-agent bash Starts a new instance of ssh-agent and your shell (bash), where you can issue commands that use a specific SSH key
ssh-add KEYFILE Adds the specified identity (private key) to the SSH agent.

Normally your private key id_rsa is automatically used by your operating system. You might have to enter your key password on each connection or the operating system may be able to store the key for the session. If you don't want to that or have to manage different key you can use ssh-agent.

SSH/SCP commands

Command Explanation
ssh user@host This is the general form of the SSH command, which connects to the specified host as the specified user
scp (-r) FROM TO This is the general form of the SCP command, which copies the specified files. The -r option copies files recursively. FROM or TO can be either local files/directories (e.g. `~/foo.bar) or remote files/directories (e.g. user@host:~/foo.bar).
ssh user@host COMMAND SSH can also directly execute remote commands without redirecting the user to a login shell.
ssh -p PORT user@host If the SSH service of the remote machine runs on a non-standard port the port can be specified with PORT
ssh -i FILE user@host FILE specifies the private key of the identity SSH should use to authentificate (can also be achieved for subsequent commands by using ssh-agent).
ssh -o OPTION user@host With that different options can be passed to the SSH client. The parameter has to be repeated for each option.
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null user@host This disables checking of host keys.
This is not recommended as it makes you vulnerable to man-in-the-middle attacks.
ssh -o UserKnownHostsFile=FILE user@hosts Specify a different file for host keys than the default ~/.ssh/known_hosts.

Similar command line parameters as for ssh above also apply to scp.

Control commands in a SSH login shell

Since SSH connections may be routed over unstable connections it can happen that the SSH session becomes unresponsive. Sometimes this happens when a lot of output is printed to the terminal. This problem is often solved by adjusting the MTU. SSH offers some control commands that can help to e.g. terminate a unresponsive session. These control commands or escape sequences use the tilde ~ character. On non-macOS keyboards this requires using the Alt Gr button. On macOS keyboards you have to use Alt + N.

Command Explanation
~? show available commands
~. terminate connection
~R request rekey (SSH 2)
~& background ssh (when waiting for connections to terminate)

Docker

Docker is a virtualization solution based on the LXC specification like e.g. OpenVZ. It is not a full virtualization but instead uses Kernel namespaces to isolate processes and resources. Because of that Docker containers are lightweight with little overhead. On the downside you cannot do everything with Docker containers that you could do with full virtualization e.g. replace the kernel. The basic Docker terminology uses images and containers. A Docker image is a pre-build snapshot of a base system with additional software and data while a Docker container is a running or stopped instance of such an image. Images are layered. The lowest layer is the base system where you can build layers on top. The idea behind that is that if you have several images based on the same base image you have to store the base image only once. With that efficient resource usage is possible. To exchange images between machines Docker uses a so called registry which is a similar concept to Git remotes. With registries you can also push and pull images. Images are created of Dockerfiles, which contain the instructions necessary to build a image. Images have to be build in order to be used in containers.

The basic idea of Docker is to have one service per container where it makes sense. If you need a webserver and a database server you should create two containers. If, on the other hand, you have a webserver that uses e.g. PHP-FPM both best live in the same container. To manage several Docker containers at once (e.g. the webserver and the database) you can use docker-compose. Docker-compose uses YAML files to specify the parameters and dependencies of the containers to be started.

Managing images

Command Explanation
docker build CONTEXT Builds the file Dockerfile in the current directory to an image. CONTEXT specifies the build context for e.g. adding files etc.
docker build -f DOCKERFILE CONTEXT Builds the file with name DOCKERFILE in the current directory to an image. CONTEXT specifies the build context for e.g. adding files etc.
docker tag HASH IMAGENAME Tags the image with the hash identifier HASH with the name IMAGENAME.
docker login REGISTRYNAME Logs into the registry with name REGISTRYNAME. May ask for credentials.
docker push IMAGENAME Pushes the image IMAGENAME to the registry. The registry URL must be part of IMAGENAME and the user must have permissions.
docker pull IMAGENAME Pulls the image IMAGENAME from the registry. The registry URL must be part of IMAGENAME and the user must have permissions.
docker images Lists the images present on the system.
docker rmi HASH/IMAGENAME or docker image rm HASH/IMAGENAME Removes the image with hash identifier HASH or name IMAGENAME from the system.

HASH is a hash code identifying a image (or a container) e.g. b461c9eec3fc.

REGISTRYNAME is a URL to a docker registry e.g. https://my-registry.domain.com

IMAGENAME is the name of an image. This is a label for a hash code and may contain the registry URL and a version tag e.g. my-registry.domain.com/project/docker-deploy:latest. docker-deploy is the name of the image, latest is the version tag and the URL before is the registry part.

Managing containers

Command Explanation
docker ps Show a list of currently running containers on the system.
docker container ls Show a list of currently running containers on the system.
docker container ls -a Show a list of all containers on the system (also stopped ones).
docker start HASH/CONTAINERNAME Start a stopped container with hash code HASH or name CONTAINERNAME.
docker stop HASH/CONTAINERNAME Stop a running container with hash code HASH or name CONTAINERNAME.
docker rm HASH/CONTAINERNAME Remove the container with hash code HASH or name CONTAINERNAME.

CONTAINERNAME is a label for the hash code.

Running containers

Command Explanation
docker run HASH/IMAGENAME COMMAND Start a container with the image identified by the hash code HASH or the name IMAGENAME and run the command COMMAND.
docker run --rm HASH/IMAGENAME COMMAND Start a container with the image identified by the hash code HASH or the name IMAGENAME and run the command COMMAND. Remove the container after execution finished.
docker run -it HASH/IMAGENAME COMMAND Start a container with the image identified by the hash code HASH or the name IMAGENAME and run the command COMMAND in interactive mode.
docker run -d HASH/IMAGENAME COMMAND Start a container with the image identified by the hash code HASH or the name IMAGENAME in the background and run the command COMMAND.
docker run --name CONTAINERNAME HASH/IMAGENAME COMMAND Start a named container identified by the name CONTAINERNAME.
docker exec HASH/CONTAINERNAME COMMAND Execute command COMMAND in the running container identified by hash code HASH or name CONTAINERNAME.
docker exec -it HASH/CONTAINERNAME COMMAND Execute command COMMAND in the running container identified by hash code HASH or name CONTAINERNAME in interactive mode.
docker exec -d HASH/CONTAINERNAME COMMAND Execute command COMMAND in the running container identified by hash code HASH or name CONTAINERNAME in the background.
docker attach HASH/CONTAINERNAME Attach stdout to a running container identified by the hash code HASH or name CONTAINERNAME.

If no name is set for the container Docker names the container in the way of adjective_famouspersonname.

Docker-compose

Command Explanation
docker-compose up Builds (if necessary), creates and starts all containers defined as services and by dependencies in the file docker-compose.yml.
docker-compose up NAME Builds (if necessary), creates and starts the container with name NAME in the file docker-compose.yml.
docker-compose -f FILE up NAME Builds (if necessary), creates and starts the container with name NAME in the file FILE.
docker-compose up -d NAME Builds (if necessary), creates and starts all containers defined as services and by dependencies in the file docker-compose.yml in the background.
docker-compose start Starts existing containers defined as services and by dependencies in the file docker-compose.yml.
docker-compose start NAME Starts the existing container defined in the file docker-compose.yml by name NAME.
docker-compose down Stops and removes all containers defined as services and by dependencies in the file docker-compose.yml.
docker-compose down NAME Stops and removes the container with name NAME defined in the file docker-compose.yml.
docker-compose stop Stops (but does not remove) all containers defined as services and by dependencies in the file docker-compose.yml.
docker-compose stop NAME Stops (but does not remove) the container with name NAME defined in the file docker-compose.yml.

Mounts and Volumes

TODO

Git

If you cannot or don't want to use Git GUIs like SourceTree or GitKraken it is a good thing to be a bit proficient on the Git command line. Below are the most important commands.

General

Command Description
git status See what is going on, on which branch you are, if you have staged, unstaged, or untracked files, if you are merging or rebasing etc.
git COMMAND -S or git COMMAND -s Cryptographically sign your action with your PGP key. (Details)
git clone URL Check out a local working copy of the repository identified by URL to the current directory
git clone URL DIR Check out a local working copy of the repository identified by URL and move the contents into the specified directory DIR

Committing

Command Description
git add FILE Add a unstaged or untracked file to the staging area
git reset FILE Remove a staged file from the staging area
git reset Remove all staged changes from the staging area
git rm FILE Remove a file from the repository (This is not the command for unstaging changes.)
git add -A Add all unstaged and untracked files to the staging area
git checkout FILE Replace a local file with its counterpart from the repository (overwrites your local changes).
git commit -m MSG commit the staged changes with the message MSG
git commit -a -m MSG Add all unstaged and untracked files to the staging area and commit the staged changes with the message MSG

Resetting Changes

Command Description
git reset --hard Resets all local changes but does not change untracked files.
git reset --hard HASH Resets the current branch to the commit specified with HASH (specified commit included).
git clean --force Removes untracked files from the repository. (This deletes data.)

Managing Remotes

Command Description
git remote -v List all remotes with their names and URLs.
git remote add NAME URL Add a new remote with the following name and URL.
git remote rm NAME Remove the remote with the following name.

Branches

Command Description
git checkout BRANCH Move the working copy to the specified branch.
git checkout -b BRANCH Create a branch from the local working copy and switch to it.
git branch (-v) List all local branches.
git branch -d BRANCH Delete a local branch.
git branch -D BRANCH Force delete a local branch.
git branch BRANCH Create a branch from the local working copy without switching to it.

Exchanging data with remotes

Command Description
git fetch Fetch new branches/tags from all remotes.
git fetch REMOTE Fetch new branches/tags from the specified remote.
git pull REMOTE BRANCH Pull changes from the specified branch of the specified remote.
git push REMOTE BRANCH Push changes to the specified branch of the specified remote.
git push REMOTE (BRANCH) --follow-tags Push changes including tags.
git push -f REMOTE BRANCH Force push changes to the specified branch of the specified remote. This rewrites git history. Never do this for branches others depend on.
git push -u REMOTE BRANCH Push changes from the specified branch of the specified remote and set the remote branch as upstream of the remote branch.
That means that the local branch tracks changes of the remote branch.

Tagging

Command Description
git tag List all local tags
git tag TAG -m MSG Create a lightweight tag with name TAG from current HEAD with the message MSG
A lightweight tag is much like a branch that does not change.
git tag -a TAG -m MSG Create a annotated (proper) tag with name TAG from current HEAD with the message MSG
git push REMOTE --follow-tags Push tags to the remote REMOTE
git tag -d TAG Delete tag TAG locally
git push --delete REMOTE TAG Delete tag TAG from remote REMOTE

Merging/Rebasing

Command Description
git merge REMOTE BRANCH Merge the specified branch into the current branch
git add -U Mark all conflicts as resolved
git merge --abort Abort merge in progress (when conflicts have occurred)
git rebase (-i) REMOTE BRANCH Rebases the current branch onto the specified branch, when the -i parameter is specified this occurs interactively
git rebase --abort Abort rebase in progress
git rebase --continue Continue rebase after resolving conflicts

Other

Command Description
git cherry-pick HASH Adds the commit specified with HASH on top of the current branch.
git revert HASH Reverts the commit specified with HASH.

MySQL

MySQL offers two command line utilities for database management: mysqladmin and mysql. Below are the most important commands.

Command Description
mysql -u USER Connect to a local MySQL instance as user USER and no password
mysql -u USER -p Like above but lets you enter the password afterwards
mysql -u USER DB Connect to a local MySQL instance as user USER and no password and immediately connect to the database DB
mysql --protocol=tcp -h HOST -u USER -p Connect to a remote MySQL instance on host HOST via TCP as user USER and prompts you for the password afterwards
mysql -u USER -p DB < import.sql Imports the contents of the file import.sql into database DB on the local MySQL instance and connects as user USER with password prompt
mysqladmin -u root password PWD Sets the root password to the password PWD
mysqladmin -u root -p ping Check if the MySQL instance is running
mysqladmin -u root -p create DB Create database DB
mysqladmin -u root -p drop DB Drop database DB
mysqladmin -u root -p flush-privileges Flush privileges after update of grant tables

The following commands on the MySQL command prompt are useful:

Command Description
exit close the MySQL session
SHOW DATABASES; lists all databases of the MySQL instance
USE DB; connects to the database DB
SHOW TABLES; lists all tables of a database
CREATE USER 'name'@'host' IDENTIFIED BY 'pwd'; creates a user with given name and host including the specified password
GRANT ALL PRIVILEGES ON DB.TABLE TO 'name '@'host'; grant all privileges on the table TABLE of database DB to the user identified by name and host
Instead of DB and TABLE you can also use the wildcard * e.g. DB.* grants rights to all tables of the specific database
FLUSH PRIVILEGES; flushes the grant tables so that newly granted privileges can become effective