Lab 19: Shell Scripting Basics

Objective

Write real shell scripts: shebang line, variables, if/else, for/while loops, functions, exit codes, and arguments. Scripts automate repetitive tasks — from backups to deployment pipelines.

Time: 35 minutes | Level: Foundations | Docker: docker run -it --rm ubuntu:22.04 bash


Step 1: Your First Script

cat > /tmp/hello.sh << 'EOF'
#!/bin/bash
NAME=${1:-World}
echo "Hello, $NAME!"
echo "Today is: $(date +%A)"
echo "You are running bash $BASH_VERSION"
EOF

chmod +x /tmp/hello.sh
/tmp/hello.sh

📸 Verified Output:

Hello, World!
Today is: Thursday
You are running bash 5.1.16(1)-release

📸 Verified Output:

💡 #!/bin/bash is the shebang — it tells the kernel which interpreter to use. Without it, the script might run with sh (less featured). Always include it as line 1.


Step 2: Variables and Arguments

📸 Verified Output:


Step 3: if / elif / else

📸 Verified Output:

📸 Verified Output:

📸 Verified Output:

💡 Common test conditions: -f file exists, -d directory exists, -z string is empty, -n string is non-empty, -eq numbers equal, -lt less than, -gt greater than.


Step 4: for Loop

📸 Verified Output:


Step 5: while Loop

📸 Verified Output:


Step 6: Functions

📸 Verified Output:


Step 7: Exit Codes

📸 Verified Output:


Step 8: Capstone — System Health Check Script

📸 Verified Output:


Summary

Concept
Syntax

Shebang

#!/bin/bash

Variable

NAME=value

Argument 1

$1

All arguments

$@

Last exit code

$?

if statement

if [ condition ]; then ... fi

for loop

for x in list; do ... done

while loop

while [ cond ]; do ... done

Function

myfunc() { ...; }

Local variable

local VAR=value

Default value

${VAR:-default}

Last updated