Advanced Shell Scripting & System Administration
Advanced Shell Scripting & System Administration
1. Advanced Shell Scripting Techniques
a. Functions in Shell Scripts:
Functions are reusable blocks of code.
Syntax:
my_function() {
echo "This is a function"
Calling:
my_function
With Parameters:
greet() {
echo "Hello, $1!"
greet "Alice"
Returning Values:
add() {
sum=$(( $1 + $2 ))
echo $sum
result=$(add 5 10)
echo "Sum is: $result"
b. Advanced String Manipulation:
Advanced Shell Scripting & System Administration
Length:
str="Hello World"
echo ${#str}
Substring:
echo ${str:6:5}
Replace:
echo ${str/World/Shell}
Remove Suffix/Prefix:
file="filename.txt"
echo ${file%.txt}
echo ${file#file}
Concatenation:
first="Hello"; second="World"; full="$first $second"
2. Scripting Best Practices and Task Automation
a. Best Practices:
- Use #!/bin/bash
- Use set -euo pipefail
- Comment your code
- Quote variables
- Use functions and "$@"
b. Automation Tools:
1. cron:
Advanced Shell Scripting & System Administration
Schedule recurring jobs.
Crontab syntax:
* * * * * command
0 2 * * * /home/user/backup.sh
Commands:
crontab -e, -l, -r
2. at:
One-time jobs.
Usage:
at 5pm
Commands: atq, atrm
3. systemd timers:
Modern scheduling.
Service File: myscript.service
Timer File: myscript.timer
Enable with:
sudo systemctl daemon-reexec
sudo systemctl enable --now myscript.timer
3. Configuring and Managing System Services
a. Commands:
sudo systemctl start/stop/restart/status <service>
sudo systemctl enable/disable <service>
b. Diagnostics:
Advanced Shell Scripting & System Administration
systemctl list-units --type=service
journalctl -xe
systemctl show <service>
c. Custom Services:
Create script /usr/local/bin/hello.py
Make executable
Create /etc/systemd/system/hello.service
Enable and start it with systemctl
Summary Table:
Shell Functions: reusable code
String Manipulation: modify strings
Automation: cron, at, systemd timers
Services: systemctl
Best Practices: quoting, set, "$@"