Cheat Sheet Linux Terminal
Published: 2021-11-19 10:50:03

- [Terminal - the command line interface (CLI)](#terminal---the-command-line-interface--cli-)
  * [Shell](#shell)
    + [“Bourne-again Shell” (Bash)](#-bourne-again-shell---bash-)
  * [SSH - Secure Shell - Connecting to remote computers](#ssh---secure-shell---connecting-to-remote-computers)
- [Commands](#commands)
  * [`ls`](#-ls-)
  * [`pwd`, `cd`](#-pwd----cd-)
  * [`man` und `--help`](#-man--und----help-)
  * [`less`, `cat`](#-less----cat-)
  * [`mkdir`, `touch`, `rm`](#-mkdir----touch----rm-)
  * [`cp`, `mv`](#-cp----mv-)
  * [Wildcards](#wildcards)
  * [`grep`](#-grep-)
  * [`find`](#-find-)
  * [`>`, `>>` (redirect operator)](#-----------redirect-operator-)
  * [`wc`, `date`, `cut`, `echo`, `tr`, `sort`](#-wc----date----cut----echo----tr----sort-)
- [User rights](#user-rights)
  * [Rights management under Linux](#rights-management-under-linux)
  * [`chmod`](#-chmod-)
    + [`chmod` in octal mode](#-chmod--in-octal-mode)
  * [`chown`](#-chown-)
  * [`chgrp`](#-chgrp-)
- [Root-rights](#root-rights)
- [User Management](#user-management)
    + [Add & Delete User](#add---delete-user)
- [| Pipe](#--pipe)
- [`history`](#-history-)
- [Shell-Skripte](#shell-skripte)
  * [variables](#variables)
    + [Predefined variables](#predefined-variables)
  * [with parameters](#with-parameters)
  * [`read`](#-read-)
- [Data stream - redirection - pipe](#data-stream---redirection---pipe)
    + [Redirect output with `>`](#redirect-output-with----)
    + [Redirect output with `>>`](#redirect-output-with-----)
    + [Redirect standard error output with `2>`](#redirect-standard-error-output-with--2--)
    + [Redirecting standard input with `<`](#redirecting-standard-input-with----)
- [Conditional statements](#conditional-statements)
  * [`if`](#-if-)
  * [`test`](#-test-)
  * [`if` one-liner](#-if--one-liner)
- [Command substitution $() and evaluation of expressions (= expr)](#command-substitution-----and-evaluation-of-expressions----expr-)
- [`case`](#-case-)
- [`for`](#-for-)
- [`while` loops](#-while--loops)
- [important root subdirectories under Linux](#important-root-subdirectories-under-linux)
- [processes](#processes)
  * [end background process](#end-background-process)
  * [status](#status)
  * [`nohup`](#-nohup-)
- [Soft- and Hardlinks](#soft--and-hardlinks)
  * [`ln`](#-ln-)
  * [Hardlinks](#hardlinks)
  * [Softlink](#softlink)
- [Hardwareinformation](#hardwareinformation)
  * [`lshw`](#-lshw-)
  * [RAM](#ram)
  * [harddisc](#harddisc)
  * [CPU](#cpu)
  * [network](#network)
  * [USB](#usb)
  * [OS](#os)
  * [hostname](#hostname)
- [More Information in German](#more-information-in-german)


####[Game](https://web.mit.edu/mprat/Public/web/Terminus/Web/main.html) to learn basic Terminal Commands


## Terminal - the command line interface (CLI) 
- open  [Strg+Alt+T] or GUI
- autocomplete with [Tab]
- history (arrowkeys)
- [Strg] [+] and [Strg] [-]
- leave it with `exit`

### Shell
[Was ist eine shell?](https://www.selflinux.org/selflinux/html/was_ist_shell.html)
- Commandlineinterpreter: changes the test in a command
- you can just type a command or use a shellscript
#### “Bourne-again Shell” (Bash)
- is one of the most popular command line programs.
- Starts with bash and ends with exit.
there are others as well as zsh, ... 

### SSH - Secure Shell - Connecting to remote computers
Determine the IP address of the Raspberry with `hostname -I`
- `ping` check the network connection
- Connect from the terminal with ssh [Username]@10.10.10.XX[IP]

## Commands
### `ls`
- `ls` [-laLi] List the contents of the directory
 - `-l` in long form
 - `-a` including the .-files
 - `-L` resolve symbolic links
 - `-i` display the i-node number
 - `-R` lists subdirectories and files recursively 
 - `-d` show directories and not content 

### `pwd`, `cd`
- `pwd` Print Working Directory
- `cd dir` Change Directory
  -`cd ..` Switching to the parent Directory.
  - return to your **own home** directory from anywhere in the file system:
    - `cd`
    - `cd $HOME`
    - `~`
 - `~max` Homedirectory of Max

### `man` und `--help`
- `man [topic]` Manualpages
- `ls --help`  prints the help for a command(here for `ls`)

### `less`, `cat`
- `less [file]` a Pager (also a read-only-Editor)/ read and control unformatted text files.
    - `q` (for quit) closes the editor again.
- `cat [file]` prints the contents of a file to the console (concatenate) or concatenates two files together 
- `head -n 10 out.dat`  - For large files, often only the beginning or the end of the file is of interest. -n is the number of lines (default 10 :))
- `tail -F out.dat` - `-F` output appended data as the file grows

### `mkdir`, `touch`, `rm`
- `mkdir [-p] dir` Make directory
  - ignore error for existing directory 
  - -p make parent directories as needed
        - `mkdir -p dir/subdir/subsubdir` 
- `touch file` creates empty file or updates timestamp
- `rm [-i] file` Remove File
 - `rm -r dir` Remove Dir. recursively

### `cp`, `mv`
- `mv [-i] [source] [destination]` move or rename file
   - if destination doesnt exist, source will be renamed to destination
  - if destination exists, source will be moved to destination
 - -i with information (ask before) 
- `cp [-i] src dst` Copy File
  - `cp -r srcdir destdir` Copy Directory
  - `cp file1 file2` copy content file1 file2, if file2 doesnt exist, it will be created, file1 will overwrite file2 


### Wildcards
- `*` string with any characters
- `?` exactly one arbitrary character
- `[...]` specification of a set of letters/ o. numbers

### `grep`
- `grep` searches patterns (e.g. words) in files grep [PATTERN] [FILE/ORDER]  & gives line with patterns
  - e.g. `grep "Lorem" travel/asia/hiking maps/map-1` 
   - for one word you can omit the quotation marks
   - search in entire directory tree, use the optio `-r`, e.g. `grep -r Lorem travel/asia/cards`, or even `grep -r lorem travel` 
 - `-o` gives just the word, not the whole line including the matching word (good for counting with wc)

### `find`
`find [LOCATION] ` searches for files/directories (_e.g. by name)_
- `find .` in current directory
- `-name [NAME]`, e.g. `find travel/asia/hiking maps -name "map*"`.
- `-user [USER]`, finds files of USER.
- `find /home -name *.jpg`, find all .jpg files in the /home and sub-directories
- `find /home -user exampleuser -mtime -7 -iname ".db"`, find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser

### `>`, `>>` (redirect operator)
 - e.G. Search for the string "ipsum" in the whole folder: `grep -r ipsum library`. Now redirect the result to a file named searchresults.txt with
 - `grep -r ipsum library > searchresults.txt`
 - `echo "Hello world" > myfile.txt`

- to not overwrite existing text use `>>`
  - `echo "How are you, world?" >> myfile.txt`

### `wc`, `date`, `cut`, `echo`, `tr`, `sort`
- `wc` wordcount  `wc -l` numbers of lines, `wc -w` words (otherswise it counts a lot of stuff)
- `date` datum 
- `cut` ausschneiden von Teilen einer Datei
  - ` -d` oder `--delimiter` + `-f` oder `--fields` 	
     - Angabe der zu extrahierenden Felder :  
     -`cut -d: -f1 /etc/passwd` gibt das 1. Zeichen vor dem Trennzeichen `:`
- `echo` im standardoutput ausgeben
- `tr` translate/ verändern (-d oder --delete)
- `sort` sortieren (zB `sort -h` sorts numeric for humans, `-u` unique)

## User rights
### Rights management under Linux 
 Users can
- only their own or data and program released for them
   - read (read:r)(directory: this can be used to retrieve the names of the files and folders it contains (but not their other data, such as permissions, owner, time of modification, file contents, etc.)
   - modify or delete (write:w)
   - and execute user programs (execute:x)
`chmod u+w a.txt`
- The access rights are  specified as 9 values ,
 - three values (rwx) represent the owner
 - next three (rwx) for the group
 - the last three (rwx) for the others.
 - not the right: `-`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0l0gcsjy3xj0eyvnvxrr.png)
 
### `chmod`
- `chmod MODUS FILE` Change access rights
- Each mode has the form: 
  - [ugoa]*([-+=]([rwxXst]*|[ugo]))+
    - u_ser_ und r_ead_
    - g_roup_    w_rite_
    - o_ther_   _e_x_ecutable_
    - a_ll_
  - `chmod u+w a.txt` User erhält Schreibrecht für a.txt
  - `chmod +x datei` Datei (für alle) ausführbar machen
  - `chmod u+rwx,g+r,o+r b.txt`
  - `chmod o-w datei` Schreibrechte für other entfernen

#### `chmod` in octal mode 
- `chmod MODE FILE` (mode = No1No2No3 )
  - Add numbers for rights
   - 0 no rights
   - 1 execute (file); "change to" (directory) [x]
   - 2 write rights [w]
   - 4 read rights [r]
   - owner [u] 1+2+4 = 7
   - Group [g] 1 +4 = 5
   - Other [o] 4 = 4 -> e.g. 754
 - `chmod 754 a.txt` -> -rwxr-xr--
 
### `chown`
Change owner with
- `chown [option] OWNER:GROUP FILE` 
- change owner (as root) R=recursive
 - `(sudo) chown -R meier /home/meier/dir`
 - `(sudo) chown -R root:admin file`
- `sudo usermod -g pi studentin`(changes useraccount // `-g` The group name or number of the user's new initial login group)

### `chgrp`
Change group owner with
 - `chgrp [option] group file`
 - Change owner group (as root)
 - `(sudo) chgrp student /home/student/xyz`

## Root-rights 
- With `sudo` command you execute command with root privileges. This is always needed, when command needs to access system files. 
- `sudo -u user [comand]` executes command as a certain user

## User Management 
- `id` prints information about the current user
- `last` which user was logged in last 
- `who` - who is logged in
- `whoami`
- `passwd`- change password 

#### Add & Delete User
- `sudo adduser studentin [id]` add a user or group to the system
- `deluser` - remove a user from the system (default home-directory stays)
  - add `--remove-home`

## | Pipe
The pipe is one of the most important tools on the Unix command line: it allows you to to chain commands, i.e. to direct the output of one command as input to the next command as input.
```
echo "Hello World" | grep World
cat suchergbnisse.txt | wc -l
wc (word count ) -l counts lines
``` 
You can also form arbitrarily long chains with pipes to evaluate from the logfile of the web server Apache2.
`cat mylogfile.log | grep "GET /library.zip" | cut -d " " -f 1 | sort -u | wc -l > "$(date)".txt` 

## `history`
- `history` -output a list of the commands entered
  -  write it to bash history immidiatly with `-w`
- `cat ~/.bash_history` file with old history entrys

## Shell-Skripte
A shell is (1) a set of commands and (2) an interpreter of
a command set. The assignment of the default shell is done in the `/etc/passwd` file on Linux systems.
A shell script is an executable file that contains commands,for example:
```
#!/bin/bash
echo "Hello World
exit 0
```
Script names usually end in .sh (for shell script), but this is just convention.
The first line is the so-called `shebang` line, which determines which shell you use.
In the example we use bash. But you can also write generically `#!/bin/sh` which is valid for all shells.

Then make the file executable:
`(sudo) chmod +x [SKRIPTNAME]`

Scripts can be executed with: `./[SKRIPTNAME]` (or absolute or relative path to the script)

-Line break marks a new command
-Alternatively, you can separate commands with semicolons `;`, but this is less readable.
-Output the return code (= value of exit) with echo $?
-Convention: If return value = 0, everything OK ("No error!")

### variables
```
#!/bin/bash
mydir=`pwd`
files=` ls -l | grep -v "insgesamt" | wc -l`
echo "Ich stehe in ${mydir} mit ${files} Dateien."
exit 0
```
#### Predefined variables
In Linux, variables are already predefined for each user, e.g. USER PWD PATH HOME USERNAME. Display the contents, e.g. with `echo $USER`. `echo ${USER}` or `echo "${USER}"` work as well. 
You can also set your own variables in the shell or in scripts:
`PARAM=VALUE`
`echo "${PARAM}"`
The variables set in an environment (a bash or program environment)can be displayed with `env` 

### with parameters
When calling scripts, space-separated parameters can be specified after the script name. In the script the content is then available via the variable $1, $2 . . . In $# the number of arguments $1 to . . . is stored.

Call e.g. like this:
`./countWordInFile.sh [DATEINAME] [WORD]`
`./countWordInFile.sh travelreport.txt "travel"`
Usage in script: $1 for first parameter, $2 for 2nd parameter, etc.
```
#!/bin/sh
grep $1 $2
```
### `read`
`read`reads standard input into variables
```bash
#!/bin/bash
echo "Wer soll gegrüßt werden? - Eingabe mit [Enter] abschließen"
read -p "Eingabe: Vorname Nachname " vorname nachname
echo "Guter Tag ${vorname} ${nachname}"
```


## Data stream - redirection - pipe
The data stream of a shell: 
-`stdin` standard input (channel 0)
usually this is input from the keyboard.
-`stout` standard output (channel 1)
standard output is usually to the screen.
-`sterr` standard error output (channel 2)
The standard output (as well as the standard output) is usually on the screen.
Often one wants to put long outputs (e.g. log files) in a file to be able to evaluate or edit them in an editor.

#### Redirect output with `>`
- Redirect the standard output of a command with: > (alternatively: 1> )
`$ du -h /home > home_size.txt`
`./myscript.sh > output_of_ascript.dat

#### Redirect output with `>>`
If you don't want to overwrite the output file, use the output redirection with `>>

#### Redirect standard error output with `2>`
The standard error output can also be redirected:
`find / -user local 2> /dev/null`

The standard output is printed to the screen, error messages such as "No authorization" are usually redirected to the standard error output. This output in the example has been redirected to /dev/null, the system's data grave.
The standard error output can also be redirected to a file:
```
find / -user local 2> find.err
find / -user local 2>> find.err
``` 

#### Redirecting standard input with `<`
The standard input (usually the keyboard), can be redirected with <. The output file find.txt of the first command serves as input in the 2nd line:
```
find / -user local 2> find.err > find.txt
grep .zip < find.txt
```
The output of grep can also be saved to another file again:
```grep .zip < find.txt > localzip.dat``` 

## Conditional statements
### `if` 
if[condition]: 
-in square brackets - example: if [ 1 = 2 ].
-or with the statement test: if test "1" = 2
keyword `then`, which introduces the statements
terminated by the keyword `fi`
*Attention* source of error: around the square brackets always belong blanks!
script hallo.sh:
``` 
#!/bin/bash
# script hallo.sh - call hallo.sh "owl
if [ "$1" == 'pingu' ]
then
echo "Hello, little penguin!"
else
echo "Hello, $1"
fi
``` 
``` 
#!/bin/bash
# call hilfe.sh [--help]
if [ "$1" == "--help" ] ;then
echo "You can always use help."
elif [ $1 ] ; then
echo "Error: parameter $1 not known."
exit 1
else
echo "Without parameter everything fine. "
echo "Parameter --help tried?"
fi
exit 0
```

### `test`
test expression # expression is true or false

Concatenating expressions:
`expression1 -a Expression2` and
`expression2 -o expression2` or
`!expression`                not
`number1 -eq number2`        true, if numbers equal
`number1 -gt number2`        true, if number1 > number2
`string1 = string2`          true, if strings equal
`string`                     true, if string is not null string

### `if` one-liner
Instead of a new line/line: `;`
`if test "1" = 1 ; then echo "true"; else echo "false";fi`

## Command substitution $() and evaluation of expressions (= expr)
```
#!/bin/sh
# command substitution $( )
# evaluation of "expressions" (= expressions)
a=$(expr 3 + 8 - 2)
# others: *,/,%,>,<,>=,... |,&
b=$(pwd)
echo "Contents of veriables a = $a "
echo "Content of the variable b = $b "
exit 0
```
Hint: Note the spaces around the expr operators!

## `case`
```
case "$variable" in
value1) command...
value2) command...
*) command...
esac
```
## `for` 
```
#!/bin/bash
for i in one two three ; do
echo "$i"
done
for i in $(ls) ; do
echo "-$i-"
done
```
## `while` loops
```
#!/bin/sh
# call: ./fakultaet.sh 10
if [ ! $1 ]; then
echo "Error: Please enter a parameter > 0 to calculate the factorial".
exit 1
fi ;
a=$1;
if [ ! $1 -o $a -le 1 -o $a -gt 20 ]; then
echo "Error: please enter a number between 1 and 20".
exit 1
fi;
fak=1;
while [ $a -ge 1 ] ; do
echo "--before: -- $a $fak"
fak=$(expr $fak \* $a)
a=$(expr $a - 1)
done
echo "fak($1) = $a"
``` 

## important root subdirectories under Linux
/bin binaries, basic commands
/boot Boot loader to start the system
/dev Device files, external devices
(e.g. hard disks, UBS devices ... Everything is a file ),
/etc system configuration for the computer
/home directory in which user directories are created 
/lib libraries and kernel modules
/media mount location for subfile systems changing data medium such as CD-ROMs
/mnt Temporarily mounted file systems
/opt Application programs
/proc Information about running processes
/root Directory of the admin user root
/sbin Binary files for system programs
/tmp storage for temporary files
/usr Program files
/var Changeable files e.g. log files
...

## processes
-programs in action 
###background process with `&` & `fg` `bg` `jobs` `^z` `kill`
Background processes are those whose process group id is different from that of the terminal. They are therefore also immune to any signals coming from the keyboard.
- `./8zauberlehrling.sh &` start bg process
- `bg` bring process to the backgound
- `fg` bring process to the foreground
- `jobs` jobs (of a terminal window) are displayed (in the same terminal window/SSH-session)
you can see: job-ID the processno. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4876sk1g8by3laomegb.png)
-  `echo $$` or `echo $BASHPID` see the process id 
- `^z` [Ctrl]-[z] pauses the process

### end background process
- bring it with `fg [NoOfJob]` to the foreground and quit with ctrl+c; 
- `kill %[NoOfJob]` 
- `kill -15 [PID]` with the Process ID (`-15` ends it normally) 
- `killall [name]`

### status
- `ps -F` (process status) - shows processes that are running (`-F` in extra Full format) show the PID (unique Process ID), TTY (Name of the Terminal running in), TIME (used CPU Time) & CMD (Command which started the process). `ps -F | grep 8zauberlehrling.sh`
- `pstree` shows the whole parent-child structure of the processes 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dho24b548ctm534ziygf.png)
- `top` (table of processes) - a dynamic overview of the processes running on the system and the system resources
   -`top -u aquinkenst` of user aquinkenst

### `nohup`
`nohup`  - suppresses the HUP signal. This allows you to start a program and keep it running even if you have logged out of the terminal or system.
 

## Soft- and Hardlinks
```bash
lisa@gateway:~$ ls -l /dev
lrwxrwxrwx 1 root root 3 Nov 24 18:46 cdrom -> sr0
lrwxrwxrwx 1 root root 3 Nov 24 18:46 dvd -> sr0
brw-rw---- 1 root cdrom 11, 0 Nov 24 18:46 sr0
crw-rw-rw- 1 root root 1, 3 Nov 24 18:46 null
crw-rw-rw- 1 root root 1, 8 Nov 24 18:46 random
brw-rw---- 1 root disk 8, 0 Nov 24 18:46 sda
brw-rw---- 1 root disk 8, 1 Nov 24 18:46 sda1
drwxr-xr-x 3 root root 240 Nov 24 18:46 snd
lrwxrwxrwx 1 root root 15 Nov 24 18:46 stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Nov 24 18:46 stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root 15 Nov 24 18:46 stdout -> /proc/self/fd/1
crw-rw-rw- 1 root tty 5, 0 Jan 11 13:17 tty
crw--w---- 1 root tty 4, 0 Nov 24 18:46 tty0
```
- `-`  for Files
- `d` for directories
- `b` for blockoriented buffered devices (e.g. hardisc)
- `c` for characteroriented unbuffered devices (e.g. keyboard, screen) 
- `l`  for softlinks

### `ln`
Create Link
`ln -s [file] [link]` softlink
`ln [file] [link]` hardlink 

### Hardlinks
A hardlink is simply an entry in the file system with a name that points to the actual location of a file. 
Different Hardlinks to the same file are exactly equivalent and it is completely irrelevant which one came first. Changes to content or file attributes affect all links (because they are actually the same file). Only when all links to a file have been deleted, the file is really deleted.
The search for hardlinks is complex, all files must be examined to see if they have the same memory location (i-node).
`find / -xdev -samefile inhalt.txt`

### Softlink 
Symbolic links work similarly to HTML links. A symbolic link is simply a small file with the l-bit set, containing the path to the target file. They lack the direct link to the actual location of the target file. If this is deleted, the link remains as a "dead link" and points from now on into the void. This can also happen when moving the target file, especially when using an absolute path in the soft link.

## Hardwareinformation
### `lshw`
`lshw` list hardware 
`lshw -c` list special class memory, disc, CPU, network

### RAM
`free -h`  Display amount of free and used memory in the system

### harddisc 
-`df` .report file system disk space `-h` human readable
- `du` disc usage - `du ~ -d 1 -h | sort -h` disc usage homedirectory `-d` depth of 1  `-h` human readable `sort -h` sort human readable numbers

### CPU
```bash
sudo lshw -C CPU
cat /proc/cpuinfo
lscpu
``` 
### network
`ip a` show / manipulate routing, network devices, interfaces and tunnels

### USB
`lsusb`

### OS
`uname -a`
`cat /etc/os-release`
`cat /proc/version`

### hostname
`hostname`
`cat /etc/hostname`

## More Information in German
http://www.netzmafia.de/skripten/unix/unix2.
-Linux - Das umfassende Handbuch /Johannes Plötner, Steffen Wendzel
[11 Shellskriptprogrammierung mit der bash](http://openbook.rheinwerk-verlag.de/linux/linux_kap11_001.html)
[14 Grundlegende Verwaltungsaufgaben](http://openbook.rheinwerk-verlag.de/linux/linux_kap14_001.html)
-IT-Handbuch für Fachinformatiker/ Sascha Kersken
[5 Betriebssystemgrundlagen](http://openbook.rheinwerk-verlag.de/it_handbuch/05_001.html)
[7 Linux](http://openbook.rheinwerk-verlag.de/it_handbuch/07_001.html)
-Selflinux
[Benutzer- und Berechtigungskonzepte unter Linux](https://www.selflinux.org/selflinux/html/nutzer_unter_linux.html)
[Benutzerverwaltung unter Linux](https://www.selflinux.org/selflinux/html/userverwaltung.html)
[Einführung in die Bourne Again Shell (bash)](https://www.selflinux.org/selflinux/html/bash_basic.html)
-Ubuntuusers
https://wiki.ubuntuusers.de/Shell/
https://wiki.ubuntuusers.de/Shell/Bash-Skripting-Guide_für_Anfänger/