Introduction to Linux: Shell Basics
Philipp Fruck & Pius Walter Shell Basics ██ Goal of this lecture ██ Use Cases:
• Introduction to shell scripting • Backup scripts
• Deployment automation ██ Why? • Log parsing and monitoring
• System maintenance tasks • Automate repetitive tasks • Improve/speedup personal workflow Introduction to Linux: Shell Basics 2 / 19
Useful (scripting) tools Tool │ Description │ Example Command ────────────┼─────────────────────────────────────────────┼────────────────────────────────── tr │ Translate or delete characters │ echo $PATH | tr : '\n'
sed │ Manipulate text (in place) │ sed -i 's/old/new/g' file.txt
cut / awk │ Text selection, e.g. print first word │ cut -d ' ' -f 1, awk '{print $1}'
basename │ Extracts the file name from a path. │ basename /path/to/file.txt
dirname │ Extracts the directory part of a file path. │ dirname /path/to/file.txt
sort / uniq │ Sorts lines and removes duplicate lines. │ sort file.txt | uniq
base64 │ Encodes and decodes data in Base64 format. │ echo "text" | base64
jq │ Parse and format JSON data. │ cat file.json | jq .
yq │ Parses and formats YAML data. │ cat file.yml | yq .
date │ Show/set system date and time. │ date -d @1730502000
time │ Measure execution time of a command │ time ls -l
sleep │ Wait for n seconds │ sleep 10
diff/delta │ Show difference between two files │ delta first.txt second.txt
Introduction to Linux: Shell Basics 3 / 19
Useful (scripting) tools Tool │ Description │ Example Command ────────────┼─────────────────────────────────────────────┼────────────────────────────────── tr │ Translate or delete characters │ echo $PATH | tr : '\n'
sed │ Manipulate text (in place) │ sed -i 's/old/new/g' file.txt
cut / awk │ Text selection, e.g. print first word │ cut -d ' ' -f 1, awk '{print $1}'
basename │ Extracts the file name from a path. │ basename /path/to/file.txt
dirname │ Extracts the directory part of a file path. │ dirname /path/to/file.txt
sort / uniq │ Sorts lines and removes duplicate lines. │ sort file.txt | uniq
base64 │ Encodes and decodes data in Base64 format. │ echo "text" | base64
jq │ Parse and format JSON data. │ cat file.json | jq .
yq │ Parses and formats YAML data. │ cat file.yml | yq .
date │ Show/set system date and time. │ date -d @1730502000
time │ Measure execution time of a command │ time ls -l
sleep │ Wait for n seconds │ sleep 10
diff/delta │ Show difference between two files │ delta first.txt second.txt
▍ If no jq is installed: cat file.json | python3 -m json.tool might help
Introduction to Linux: Shell Basics 4 / 19
Useful (scripting) tools Tool │ Description │ Example Command ────────────┼─────────────────────────────────────────────┼────────────────────────────────── tr │ Translate or delete characters │ echo $PATH | tr : '\n'
sed │ Manipulate text (in place) │ sed -i 's/old/new/g' file.txt
cut / awk │ Text selection, e.g. print first word │ cut -d ' ' -f 1, awk '{print $1}'
basename │ Extracts the file name from a path. │ basename /path/to/file.txt
dirname │ Extracts the directory part of a file path. │ dirname /path/to/file.txt
sort / uniq │ Sorts lines and removes duplicate lines. │ sort file.txt | uniq
base64 │ Encodes and decodes data in Base64 format. │ echo "text" | base64
jq │ Parse and format JSON data. │ cat file.json | jq .
yq │ Parses and formats YAML data. │ cat file.yml | yq .
date │ Show/set system date and time. │ date -d @1730502000
time │ Measure execution time of a command │ time ls -l
sleep │ Wait for n seconds │ sleep 10
diff/delta │ Show difference between two files │ delta first.txt second.txt
▍ If no jq is installed: cat file.json | python3 -m json.tool might help
▍ ⚠️ uniq only works with sorted input, always use <command> | sort | uniq to avoid mistakes
Introduction to Linux: Shell Basics 5 / 19
Exit Codes On Linux, every command returns an exit code ($?) indicating success or failure.
An exit code is always in the range 0-255.
Only 0 indicates success, every other exit code indicates a failure. true
echo Output of true: $?
false
echo Output of false: $?
——————————————————— [finished] ———————————————————
Output of true: 0 Output of false: 1 Introduction to Linux: Shell Basics 6 / 19
Exit Codes On Linux, every command returns an exit code ($?) indicating success or failure.
An exit code is always in the range 0-255.
Only 0 indicates success, every other exit code indicates a failure. true ls /tmp
echo Output of true: $? echo "Exit code of ls: $?"
false grep "foo" file.txt
echo Output of false: $? echo "Exit code of grep: $?"
——————————————————— [finished] ———————————————————
Output of true: 0 Output of false: 1 Introduction to Linux: Shell Basics 7 / 19
Exit Codes On Linux, every command returns an exit code ($?) indicating success or failure.
An exit code is always in the range 0-255.
Only 0 indicates success, every other exit code indicates a failure. true ls /tmp
echo Output of true: $? echo "Exit code of ls: $?"
false grep "foo" file.txt
echo Output of false: $? echo "Exit code of grep: $?"
——————————————————— [finished] ——————————————————— ▍ The exit command can be used to quit an interactive
▍ shell
Output of true: 0 ▍ See man errno or man sysexits.h for common C exit codes
Output of false: 1 Introduction to Linux: Shell Basics 8 / 19
Concatenating Commands The POSIX standard allows chaining commands in multiple ways:
Hello 1 Hello 2
# Sequential execution: commands runs regardless of Hello 3
result Hello 4
false; echo Hello 1 Hello 5
true; echo Hello 2
# Conditional execution: run next only if previous
succeeds
true && echo Hello 3 255 ./01-core-commands.md
# Conditional execution: run next only if previous 636 ./08-services-and-remote-access.md
fails 526
false || echo Hello 4 ./09-storage-and-system-security.md
# Run commands in sub-group 938 ./10-markup-languages.md
true && (false; echo Hello 5) 255 ./02-system-tools.md
311 ./03-shell-basics.md
491 ./00-overview.md —————————————————————————— [finished] —————————————————————————— 362 ./06-basic-permissions.md
370 ./07-advanced-permissions.md 415 ./04-posix-and-bash-syntax.md
# Command substition: Get line count of all slides 471 ./05-scripting.md
wc -l $(find . -type f) 5030 total
# legacy substitution syntax, just so you know Running in
echo "Running in `pwd`" /home/runner/work/lecture-introduction-to
-linux/lecture-introduction-to-linux/slid
es ————————————————————— [finished] ——————————————————————
Introduction to Linux: Shell Basics 9 / 19
File Descriptors ██ Manage input/output streams ██ File descriptor IDs
• 0 → stdin
# Redirect stdout to a file (overwrite content) • 1 → stdout
echo "Hello" > output.txt • 2 → stderr
• Custom FDs start at 3.
# Append stdout to a file
echo "Hello 2" >> output.txt
# Redirect stderr to hide messages
ls non_existing_file 2> /dev/null
# Redirect both stdout and stderr
command &> combined.txt
# Create custom FD and write to it
exec 3> output.txt
echo "Hello, World!" >&3
exec 3>&- # Close the FD
# Bash feature: Use command output as file input
diff <(ls first) <(ls second)
Introduction to Linux: Shell Basics 10 / 19
File Descriptors ██ Manage input/output streams ██ File descriptor IDs
• 0 → stdin
# Redirect stdout to a file (overwrite content) • 1 → stdout
echo "Hello" > output.txt • 2 → stderr
• Custom FDs start at 3.
# Append stdout to a file
echo "Hello 2" >> output.txt ██ Writing to a file without an editor
# Redirect stderr to hide messages
ls non_existing_file 2> /dev/null cat > newfile.txt <<EOF
this
# Redirect both stdout and stderr is
command &> combined.txt the
content
# Create custom FD and write to it of my
exec 3> output.txt textfile
echo "Hello, World!" >&3 EOF
exec 3>&- # Close the FD
# Bash feature: Use command output as file input ▍ Instead of <<EOF, you can use cat > newfile.txt and hit
diff <(ls first) <(ls second) ▍ ^C to stop writing to the file
Introduction to Linux: Shell Basics 11 / 19
Pipes The output of one command can be piped into another command to work with it (instead of a file): ls / | grep bin
———————————————— [finished] —————————————————
bin sbin Introduction to Linux: Shell Basics 12 / 19
Pipes The output of one command can be piped into another command to work with it (instead of a file): ls / | grep bin
———————————————— [finished] —————————————————
bin sbin Pipes only capture stdin: ls /root/ | grep --only Perm
——————————— [finished with error] ———————————
ls: cannot open directory '/root/': Permission denied Introduction to Linux: Shell Basics 13 / 19
Pipes The output of one command can be piped into File descriptors to the rescue!
another command to work with it (instead of a file):
ls /root/ 2>&1 | grep --only Perm
ls / | grep bin
——————————————————— [finished] ———————————————————
———————————————— [finished] —————————————————
Perm bin sbin Pipes only capture stdin: ls /root/ | grep --only Perm
——————————— [finished with error] ———————————
ls: cannot open directory '/root/': Permission denied Introduction to Linux: Shell Basics 14 / 19
Pipes The output of one command can be piped into File descriptors to the rescue!
another command to work with it (instead of a file):
ls /root/ 2>&1 | grep --only Perm
ls / | grep bin
——————————————————— [finished] ———————————————————
———————————————— [finished] —————————————————
Perm bin sbin Infinite piping possible!
Pipes only capture stdin: curl https://api.github.com/users/p-fruck/keys 2
>/dev/null | jq .[0].key | tr -d '"' | ssh-keygen -lf
-
ls /root/ | grep --only Perm
▍ Note: -f - means --file: stdin and reads the input from the pipe
——————————— [finished with error] ———————————
# spying on our students on the remote system
ls: cannot open directory '/root/': last | grep '^s26' | cut -d ' ' -f 1 | sort | uniq |
Permission denied wc -l
Introduction to Linux: Shell Basics 15 / 19
Globbing ██ Globbing (Filename Expansion) ██ Example:
Globbing lets you match filenames using wildcards:
# List all .txt files
Pattern │ Matches ls *.txt
────────┼─────────────────────────────────
* │ Any string, including empty # List files starting with a or b
? │ Any single character ls [ab]*.txt
[abc] │ Any one of the listed characters
[!abc] │ Any character not listed
Introduction to Linux: Shell Basics 16 / 19
Persisting Configuration ██ How it works • Previous settings like alias are set on per-session basis
• All shells support configuring persistent settings using configs • On Bash: ~/.bash_profile and ~/.bashrc are used
◦ They load further files from ~/.bashrc.d/*
◦ Other shells like ZSH provide e.g. ~/.zshrc
• System-wide config is provided via /etc/profile, /etc/bashrc and /etc/profile.d/*.sh
• Config files are just shell scripts • You can load them manually by running source script.sh (Bash) or . script.sh (POSIX)
Introduction to Linux: Shell Basics 17 / 19
Persisting Configuration ██ How it works • Previous settings like alias are set on per-session basis
• All shells support configuring persistent settings using configs • On Bash: ~/.bash_profile and ~/.bashrc are used
◦ They load further files from ~/.bashrc.d/*
◦ Other shells like ZSH provide e.g. ~/.zshrc
• System-wide config is provided via /etc/profile, /etc/bashrc and /etc/profile.d/*.sh
• Config files are just shell scripts • You can load them manually by running source script.sh (Bash) or . script.sh (POSIX)
▓▓▓ Differences Feature │ ~/.bash_profile & /etc/profile │ ~/.bashrc & /etc/bashrc
──────────────┼────────────────────────────────────────┼───────────────────────────────────────── Type of Shell │ Login shells │ Non-login interactive shells
When executed │ At login (e.g., SSH, virtual terminal) │ For every new interactive terminal
Common Use │ Environment variables, session setup │ Aliases, functions, interactive settings
Introduction to Linux: Shell Basics 18 / 19
Thank you! Thank you for your attention! Don't forget the feedback in Moodle please! Introduction to Linux: Shell Basics 19 / 19