Linux Server setup

Bash Cheat Sheet

A list of common Linux commands used mainly on this site.


Info, Help, Instruction

man (manual)

The man pages are help files for handling and explaining the options of commands and programs. The command man is followed by the command as a paramater:

__$ man cd

A Manpage can be searched with a slash followed by a search word: /searchword. Use n to jump to the next search hit. q to exit.

The man command also has instructions:

__$ man man

type

Gives information about a command, whether it is internal, external or an alias. This command is also useful to find out if a command is implemented.

__$ type cd

which

Prints the path of an executable file specified in the PATH environment variable.

__$ which cd

-a prints all paths to an executable file.

__$ which -a cd

history

Outputs the history of the entered terminal commands.

__$ history

Delete the history file with -c.

__$ history -c

Set the maximum number of entries to 10,000.

__$ export HISTSIZE=10000

File system

pwd (print working directory)

Prints the current directory path. Rather useful in shell scripts!

__$ pwd

cd (change directory)

Without any further specification it changes to the home directory:

__$ cd

Change to a directory with absolute path:

__$ cd /absolute/path

Change to a directory with relative path

__$ cd /relative/path

Paths with spaces are enclosed in quotation marks:

__$ cd "a path/with space/somewhere"

Change one directory level higher:

__$ cd ..

One directory level higher and change relatively from there:

__$ cd ../path/from/there

Go back to the previous directory:

__$ cd -

Change to the home directory:

__$ cd

ls (list)

Outputs the contents of a directory.

__$ ls

Output as a detailed list with -l:

__$ ls -l

Output also of hidden files with -a:

__$ ls -a

Common use:

__$ ls -la

List detailed (-l), all (-a), sorted by time (-t), and in reverse order (-r):

__$ ls -latr

With path specification:

__$ ls -la /etc

Scroll through long outputs with less (or more):

__$ ls -la /etc | less

Alias ~ lists the home directory:

__$ ls ~

stat (status)

Display information about files and folders.

__$ stat my-file.txt

Less details with -t:

__$ stat -t my-file.txt

touch

Changes the modification date of files. If the file does not exist, it will be created.

__$ touch ma-new-file.txt

Change the access and change timestamp to 12/31/2020 12:45:30 with -t:

__$ touch -t 201231124530 my-old-file.txt

Change the modification timestamp (-m) to 12/31/2020 12:45:30 with -t:

__$ touch -t 201231124530 my-old-file.txt

Change the access timestamp (-a) to 12/31/2020 12:45:30 with -t:

__$ touch -t 201231124530 my-old-file.txt

cp (copy)

Copies files and folders:

__$ cp file.txt new/path/file.txt

Copy multiple files and folders:

__$ cp file.txt folder new/path/

Copy subdirectories with -r:

__$ cp -r folder new/path/

Attributes retained -a (owner, group and access rights / creation, modification and access data):

__$ cp -a file.txt new/path/

Interactive mode! Ask -i before overwriting:

__$ cp -i file.txt new/path/

Save files with the same name -b:

__$ cp -b file.txt new/path/

mv (move)

Move or rename files and folders.

Rename file-a.txt to file-b.txt:

__$ mv file-a.txt file-b.txt

Move file-a.txt to path/file-a.txt:

__$ mv file-a.txt path/file-a.txt

Move and rename file-a.txt to path/file-b.txt:

__$ mv file-a.txt path/file-b.txt

Move file-a.txt and ornder-b into folder-c:

__$ mv file-a.txt folder-b folder-c/

Rename file extension of multiple files:

__$ mv *.JPG *.jpg

mkdir (make directory)

Create directories:

__$ mkdir folder-a

Create multiple directories:

__$ mkdir folder-a folder-b

Create a directory, create parent folders with, if necessary -p:

__$ mkdir -p folder-a/folder-b/folder-c

Create directory trees with curly braces {folder}:

__$ mkdir -p folder-a/{folder-b, folder-c}/{folder-1, folder-2}

This creates the structure:


|-- folder-a
	|-- folder-b
		|-- folder-1
		|-- folder-2
	|-- folder-c
		|-- folder-1
		|-- folder-2

rm (remove)

Delete files and directories:

__$ rm file.txt

Delete multiple files and directories including subdirectories -r:

__$ rm -r file.txt folder

Delete all files with the extension .jpg:

__$ rm *.jpg

Delete without asking -f:

__$ rm -f file.txt

Delete with demand -i. Interactive mode!

__$ rm *.jpg

rmdir (remove directory)

Delete empty directories:

__$ rmdir empty-folder

Delete parent directories as well -p:

__$ rmdir -p folder-a/folder-b/folder-c

ln (link)

Creates a link to a file or directory. The -s parameter creates a symbolic or soft link.

__$ ln -s /path/to/source-file.txt new-symbolic-link

gzip

Pack file.txt to file.txt.gz:

__$ gzip file.txt

Pack a folder to folder.gz:

__$ gzip folder

Pack multiple files individually (Output file1.txt.gz,file2.txt.gz, file3.txt.gz):

__$ gzip file1.txt file2.txt file3.txt

Unzip an archive:

__$ gzip -d archive.gz

echo

For outputting strings and variables in standard output, for example the terminal:

__$ echo "My username is $USER"

cat (concatenate)

Merges files or prints the contents of a file in the terminal:

__$ cat /etc/hostname

less

Outputs the contents of a file in the terminal with the advantage of being able to scroll long outputs (scroll with the arrow keys and quit with q):

__$ less ~/.bashrc

tail

Outputs the last lines of a file. Without specifications, the last 10 lines are output:

__$ tail /var/log/auth.log

Output of the last 5 lines with -n:

__$ tail -n5 /var/log/auth.log

Show changes of a file live with -f:

__$ tail -f /var/log/auth.log

grep

Search files for strings or regular expressions:

__$ grep "searchword" /var/log/auth.log

wc (word count)

Counts words, lines, characters or bytes of a text file.

Count lines with -l:

__$ wc -l /var/log/auth.log

Count words with -w:

__$ wc -w /var/log/auth.log

Count characters with -m:

__$ wc -m /var/log/auth.log

Count bytes with -c:

__$ wc -c /var/log/auth.log

Length of the longest line with -L:

__$ wc -L /var/log/auth.log

> (redirect and replace)

Redirects an output, for example to a file. The contents of the file are overwritten:

__$ echo "My new Text" > ~/file.txt

>> (redirect and append)

Redirects an output and writes it to the end of a file:

__$ echo "More text to the end of the file." >> ~/file.txt

sed (stream editor)

Replaces text in a file according to a search pattern or regular expression. sed is a non-interactive text editor.

Replace all occurrences of "old-text" with "new-text":

__$ sed -i 's/old-text/new-text/g' file.txt

Removes the hash symbol (#) at the beginning of the line from #force_color_prompt and comments it in:

__$ sed -i '/^#force_color_prompt *=/s/^#//' ~/.bashrc

Changes the value of a configuration line:

__$ sed -i 's/\(ConfigurationAttributes[\t[:space:]]*=[\t[:space:]]*\).*/\1 newValue/g' ~/file.conf

nano

A simple text editor that can be run from the terminal. Show full list of keyboard shortcuts with CTRL+g.

With nano a new file can also be created:

__$ nano ~/new-file.txt

The most important keyboard shortcuts:

  • CTRL+s save
  • CTRL+o save as
  • CTRL+x close
  • CTRL+k cut or delete whole line
  • CTRL+ALT+↑ copy
  • CTRL+ALT+u paste
  • CTRL+w search
  • ALT+w continue searching

vim (vi improved)

A comprehensive text editor that can be run from the terminal.

With vim a new file can also be created:

__$ vim ~/new-file.txt

The most important keyboard shortcuts:

  • :wq save
  • :q close
  • :q! close and discard changes
  • ESC normal mode
  • i insert mode
  • x delete mode

It is worth working through the vim learning course:

__$ vimtutor

System, Hardware, Network, Monitoring

getent (get entries)

Reading out important system information stored in databases (text files). Very useful to get a quick overview of users, groups and network. The possible sources can be retrieved via the first parameter: ahosts, ahostsv4, ahostsv6, aliases, ethers (Ethernet addresses), group, gshadow, hosts, netgroup, networks, passwd, protocols, rpc, services, shadow.

List all user accounts with passwd.

__$ getent passwd

Readout of a specific user:

__$ getent passwd tom

Show groups:

__$ getent groups

hostnamectl

Read and edit the hostname and related settings:

__$ hostnamectl

lsb_release

Information about LSB (Linux Standard Base) and distribution. All information with -a:

__$ lsb_release -a

os-release

os-release is a file with information about the operating system:

__$ cat /etc/os-release

uname

Output system information about the kernel. All information with -a:

__$ uname -a

top

Displays running processes with current changes:

__$ top

htop

Displays running processes and utilization of memory and processor with current changes:

__$ htop

lsblk

Lists storage devices (Block Devices):

__$ lsblk

df (disk free)

Shows the free disk space. With -h the units are output in larger units:

__$ df -h

-all includes all file systems:

__$ df -all

By specifying a path, only the partition where the file or folder is located is considered (the current directory is specified with a dot df .):

__$ df /home

du (disk usage)

Displays the used disk space. With -h the units are output in larger units:

__$ du -h

-all includes all file systems:

__$ du -all

By specifying a path, only the partition where the file or folder is located is considered (the current directory is specified with a dot du .):

__$ du /home

free memory

Information about the used and unused memory:

__$ free

With -h the units are output in larger units:

__$ free -h

reboot

Restart of the operating system.

__$ reboot

poweroff

Switch off the computer.

__$ poweroff

ps (processes)

Manages processes.

Display the complete process list:

__$ ps ax

Process list with extended information:

__$ ps axu

Running processes:

__$ ps -r

Display specific process by process ID (PID):

__$ ps 1

pstree

Displays the process list in a tree structure:

__$ pstree

pgrep

Filter processes based on a search term.

Displays all processes with "ssh" in the process name:

__$ pgrep ssh

kill

Terminates a process by sending a signal to a process ID (PID). Standard signal is 15 or -SIGTERM. With this signal the process has the possibility to terminate itself cleanly. -SIGKILL or 9 terminates a process immediately.

Terminates process 555 with -SIGTERM:

__$ kill 555

Terminates the process 555 with -SIGKILL:

__$ kill -9 555

killall

Terminates all processes that match a process name.

Terminate processes with the name "apache":

__$ killall apache

Exact match of the process name with -e:

__$ killall -e apache

Interactive exit with -i. Ask before each exit:

__$ killall -i apache

systemctl

Program package to manage system and session manager systemd.

Listing of all system units with list-units:

__$ systemctl list-units

Listing of all timed system units with list-timers:

__$ systemctl list-timers

Start a system unit with start:

__$ systemctl start ssh

Stopping a system unit with stop:

__$ systemctl stop ssh

Restart a system unit with restart:

__$ systemctl restart ssh

Restart a system unit and reload associated configuration files with reload:

__$ systemctl reload ssh

Display status of a system unit with status:

__$ systemctl status ssh

Load system unit at system startup with enable:

__$ systemctl enable ssh

System unit does not load with disable at system startup:

__$ systemctl disable ssh

Check if system unit loads with is-enabled at system startup:

__$ systemctl is-enabled ssh

Reload the systemd configuration files daemon-reload:

__$ systemctl daemon-reload

ip

Program package for network interface management.

Show IP address with a

__$ ip a

Show network interfaces with link.

__$ ip link

ping

Check accessibility of other computers:

__$ ping 192.0.0.1

dig (domain information groper)

Queries DNS information:

__$ dig wikipedia.org

Query the mail server entry with mx:

__$ dig wikipedia.org mx

nslookup

With nslookup (Name Server Lookup) DNS information can be retrieved.

Translate a domain to an IP:

__$ nslookup wikipedia.org

Reverse DNS Lookup:

__$ nslookup 91.198.174.192

Query the NS Record:

__$ nslookup -type=ns wikipedia.org

Query all NS Records:

__$ nslookup -type=any wikipedia.org

Query the MX Record:

__$ nslookup -type=mx wikipedia.org

Use nslookup interactively (exit with exit):

__$ nslookup

ssh

Secure Shell is a protocol for encrypted network communication.

Simple SSH connection via standard port 22:

__$ ssh 192.0.0.1

SSH connection via port 2222 with -p:

__$ ssh 192.0.0.1 -p 2222

SSH connection via port 2222 (-p) and private key (-i):

__$ ssh 192.0.0.1 -p 2222 -i path/key

wget

Download files from FTP, HTTP or HTTPS servers.

Download to the current directory:

__$ wget http://example.com/file.tar

Save with different file name (-O):

__$ wget -O new-name.tar http://example.com/file.tar

Download to another directory (-P):

__$ wget http://example.com/file.tar -P /tmp

lsof

Utility to list open files. Since everything is a file under Linux, it can also be used to read open ports.

List open ports (filtered with the search word "LISTEN"):

__$ lsof -i -P | grep LISTEN

netstat

Command line program for network interface diagnostics.

Show all network interfaces:

__$ netstat

List all open ports:

__$ netstat -lptn

Observe specific port:

__$ netstat -pan | grep 80

tcpdump

Packet sniffer. Logs network events.

Show network interfaces:

__$ tcpdump -D

Log network events from port 443:

__$ tcpdump -n -i enp1s0 port 443

Log network events with IP 1.2.3.4:

__$ tcpdump -n -i enp1s0 | grep 1.2.3.4

Write network events from port 443 to the log.txt file:

__$ tcpdump -n -i enp1s0 port 443 -w log.txt

ufw (uncomplicated firewall)

Default firewall.

Check status with status:

__$ ufw status

Detailed status with status verbose:

__$ ufw status verbose

Output rule table with rule numbers status numbered:

__$ ufw status numbered

Enable with enable:

__$ ufw enable

Disable with disable:

__$ ufw disable

Block everything incoming:

__$ ufw default deny incoming

Allow all outgoing:

__$ ufw default allow outgoing

Allow a service with allow:

__$ ufw allow ssh

Allow a port over TCP with allow:

__$ ufw allow 3000/tcp

Block a port with deny:

__$ ufw deny 3000

Delete rule via rule number with delete:

__$ ufw delete 5

Rule Reload table with reload:

__$ ufw reload

List of all applications app list:

__$ ufw app list

Information about a specific application app info:

__$ ufw app info "Nginx Full"

Prüfen ob Logging aktiviert ist:

__$ ufw status verbose

Log-Level ändern:

  • fff: Kein verwaltetes Logging.
  • on (low, Standard): Protokolliert alle blockierten Pakete, die nicht der definierten Richtlinie (mit Verbindungsratenbegrenzung) entsprechen, sowie Pakete, die den protokollierten Regeln entsprechen.
  • on (medium): Protokollierungsstufe niedrig, sowie alle erlaubten Pakete, die nicht der definierten Richtlinie entsprechen, alle INVALID-Pakete und alle neuen Verbindungen. Die gesamte Protokollierung erfolgt mit Verbindungsratenbegrenzung.
  • on (High): Protokollebene mittel (ohne Verbindungsratenbegrenzung), plus alle Pakete mit Verbindungsratenbegrenzung.
  • on (Full): Protokollierungsstufe hoch ohne Verbindungsratenbegrenzung.
__$ ufw logging medium

Log Dateien von ufw:

__$ ls /var/log/ufw*

Alle Log Dateien ausgeben:

__$ less /var/log/ufw*

Protokollierung live mitlesen:

__$ tail -f /var/log/ufw.log

Users, groups and rights management

whoami

Outputs the currently logged in user name:

__$ whoami

su (substitute user)

Changes the user:

__$ su tom

The option - or -l changes the user and simulates a real login with changing the home directory, changing the shell settings and setting the environment variables of the user:

__$ su - tom

Use a shell -s with a different user -u:

__$ sudo -s -u tom

logout

Logs out the user:

__$ logout

passwd

To change the password:

__$ passwd

Changing the password from the user tom:

__$ passwd tom

users

Outputs the currently logged in user name (similar to whoami):

__$ users

List all users:

__$ less /etc/passwd

The /etc/passwd file contains some information about all user accounts. The structure of a line has the following meaning:

root:x:0:0:root:/root:/bin/bash

  • root: Username
  • x: Password is set
  • 0: UID (User ID)
  • 0: GID (Group ID)
  • root: Comment
  • /root: Home directory
  • /bin/bash: Standard shell program

List users with search filter. Every line in which root occurs:

__$ less /etc/passwd | grep root

adduser

Create a new user interactively:

__$ adduser tom

Add a user to an existing group:

__$ adduser tom groupname

Create a new user without any further information --gecos:

__$ adduser --gecos "just tom" tom

Create a new system user systom:

__$ adduser --system --group systom
  • --system: System user
  • --group: in combination with --system, the same name is used for the group

Create a new system user systom with additional parameters:

__$ adduser --system --group --disabled-password --shell /bin/bash --home /home/systom systom
  • --disabled-password: do not set password, therefore no password based user login possible, but SSH login allowed
  • --shell: the shell after login
  • --home: user home directory

deluser (delete user)

Deletes a user account including the user files:

__$ deluser tom

Remove a user from a group:

__$ deluser tom groupname

usermod

Change a user account.

Add another group to a user (previous groups are preserved):

__$ usermod -aG groupname tom

groups

Lists the primary and supplementary groups:

__$ groups

List groups of specific users (root, tom, syslog):

__$ groups root tom syslog

groupadd

Create groups:

__$ groupadd nameofnewgroup

groupdel

Delete group:

__$ groupdel nameofgroup

groupmod

Changing a group. For example, change the group name oldname to newname with the -n option.

__$ groupmod -n newname oldname

chown (change owner)

Change the owner of a file or folder.

tom becomes the new owner of the /var/www/site:

__$ chown tom /var/www/site

tom becomes the new owner of the /var/www/site and all files and folders contained therein with -R:

__$ chown -R tom /var/www/site

tom tom and the group of the same name become the new owner of the /var/www/page folder:

__$ chown tom:tom /var/www/site

chmod

Changes the access rights of files and folders. The permissions are specified numerically (octal) or symbolically.

The symbolic character sequence of a rights write has ten digits, which are divided into four groups - --- --- --- (the notation does not actually provide for spaces, they are just for illustration in this example):

  • first group (character 1): shows whether it is a file (-) or a directory (d)
  • second group (characters 2-4): owner rights; read, write, execute
  • third group (characters 5-7): group rights; read, write, execute
  • fourth group (characters 8-10): other rights; read, write, execute

Example: d rwx r-x r-x (corresponds numerically to 755):

  • d: it is a directory
  • rwx: Owner may read, write, execute
  • r-x: Group may read, execute
  • r-x: Others may read, execute

Example: - rwx rwx rwx (corresponds numerically to 777):

  • -: it is a file
  • rwx: Owner may read, write, execute
  • rwx: Group may read, write, execute
  • rwx: Others may read, write, execute

Example: - rw- r-- r-- (corresponds numerically to 644):

  • -: it is a file
  • rw-: Owner may read, write
  • r--: Group may read
  • r--: Others may read

Change the access rights numerically to 755 of the file.txt file:

__$ chmod 755 file.txt

Change the access rights numerically to 655 of the folder folder and all the files and folders it contains with -R:

__$ chmod -R 755 file.txt

Change the access rights symbolically (corresponding to numerically 777) of the file file.txt. a stands for all. + stands for add. rwx stands for read, write, execute:

__$ chmod a+rwx file.txt

chgrp (change group)

Changes the group membership of files or folders.

Set group tom as the new owner of the folder /var/www/site:

__$ chgrp tom /var/www/site

APT - Package Management (Advanced Packaging Tool)

apt install

Installs a package. For example, dnsutils:

__$ apt install dnsutils

apt remove

Removes a package. Any configuration files and the like that have been created are retained:

__$ apt remove dnsutils

apt purge

Removes configuration files and the like from packages that have already been uninstalled:

__$ apt purge dnsutils

apt update

Gets package information of all configured sources and updates the package list:

__$ apt update

apt upgrade

Updates packages that are listed in the package list:

__$ apt upgrade

apt full-upgrade

Similar to upgrade, additionally removes packages if necessary. Should be used instead of upgrade when upgrading the system as a whole:

__$ apt full-upgrade

apt show

Displays information about a package:

__$ apt show dnsutils

apt list

Lists all installed packages with --installed:

__$ apt list --installed

Query a specific installed package with --installed and a search word with placeholder opens*:

__$ apt list --installed opens*

Lists all renewable packages with --upgradeable:

__$ apt list --upgradeable

Lists all available versions with --all-versions:

__$ apt list --all-versions

Searches online for available packages. For example, dnsutils:

__$ apt search dnsutils

apt autoremove

Removes packages that are no longer needed, for example, packages that were installed due to other dependencies:

__$ apt autoremove

apt clean

Cleans up the archive folder for packages /var/cache/apt/archives/:

__$ apt clean