Introduction to Linux: Scripting                                          
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                            Philipp Fruck & Pius Walter                                                            
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                Scripting                                                                 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            ██ Goal of this lecture                                          ██ Use Cases:                                                         
                                                                                                                                                   
               •  Learn practical scripting pitfalls and best                   •  Writing robust, production-ready scripts                        
                  practices                                                     •  Managing long-running or background tasks                       
               •  Get familiar with editors and process/job control             •  Editing files directly on remote servers                        
                                                                                                                                                   
            ██ Why?                                                                                                                                
                                                                                                                                                   
               •  Real-world scripts must handle errors and edge                                                                                   
                  cases safely                                                                                                                     
               •  Editors and job control are daily tools for any                                                                                  
                  Linux user                                                                                                                       
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                   2 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                Functions in POSIX / Bash                                                 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            ██ Functions allow reusable blocks of code                                   ██ Function return values                                 
                                                                                                                                                   
               •  Functions improve code clarity and reduce repetition.                                                                            
               •  Parameters passed to a function or script are accessed via $1,            1 #!/usr/bin/env bash                                  
                  $2, ...                                                                   2                                                      
                  ◦  $0 is the invoked executable (remember C's argv[0]?)                   3 # the function keyword only exists in                
                  ◦  $# shows the parameter count                                             bash                                                 
                  ◦  $@ shows all parameters (starting at $1)                               4 function add() {                                     
                  ◦  shift drops the first n parameters (by default 1)                      5     echo $(( $1 + $2 ))                              
                                                                                            6 }                                                    
                                                                                            7                                                      
                    #!/bin/sh                                                               8 # Functions can return plaintext                     
                    myfunc() {                                                              9 sum=$(add 3 5)                                       
                        echo "Hello from $0"                                               10 echo "Sum = $sum"                                    
                        echo "$# args: $@"                                                 11                                                      
                        echo "First: $1" ; shift ; echo "New first: $1"                    12 # And functions can return status                    
                    }                                                                         codes                                                
                    myfunc foo bar                                                         13 check_file() {                                       
                                                                                           14     [ -f "$1" ] # same as return                     
                                                                                              0/1/255                                              
                  —————————————————————— [finished] ——————————————————————                 15 }                                                    
                                                                                           16                                                      
                                                                                           17 check_file ../README.md && echo                      
                    Hello from                                                                Exists!                                              
                    /home/runner/work/_temp/nix-shell.0FChq9/.presentermE                                                                          
                    Dgdnd/script.sh                                                                                                                
                    2 args: foo bar                                                      ———————————————— [finished] —————————————————             
                    First: foo                           Introduction to Linux: Scripting                                                   3 / 14 
                    New first: bar                                                                                                                 
                                                                                           Sum = 8                                                 
                                                                                                                                                   
                                                                                                                                                   
                                                         Asking for Input                                                          
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            Besides parameters, scripts can also ask the            read stores a line of input in a variable:                                     
            user questions at runtime:                                                                                                             
                                                                       •  -p : show a prompt                                                       
                                                                       •  -r : raw, do not interpret backslash as an escape character              
              #!/bin/sh                                                •  -s : silent, do not echo the input (e.g., for passwords)                 
              read -r -p "Your name: " name                                                                                                        
              echo "Hello, $name!"                                                                                                                 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                   4 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                 For Loop                                                                  
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            ██ POSIX for loop                                                ██ Bash set notation                                                  
                                                                                                                                                   
                                                                             While not strictly related to for loops bash also                     
                 # Iterate over numbers                                      supports set notation:                                                
                 for i in 0 1 2 3 4 5 6 7 8 9 10; do                                                                                               
                     echo -n "$i "                                                                                                                 
                 done                                                             echo {1..10}                                                     
                 echo                                                             echo {A..C}{1..3}                                                
                 # Loop over files (pipe output into head)                        for i in {1..10}; do echo -n $i,; done                           
                 for file in *.md; do                                                                                                              
                     echo "File: $file"                                                                                                            
                 done | head -n 5                                               ——————————————————— [finished] ———————————————————                 
                                                                                                                                                   
                                                                                                                                                   
               ——————————————————— [finished] ———————————————————                 1 2 3 4 5 6 7 8 9 10                                             
                                                                                  A1 A2 A3 B1 B2 B3 C1 C2 C3                                       
                                                                                  1,2,3,4,5,6,7,8,9,10,                                            
                 0 1 2 3 4 5 6 7 8 9 10                                                                                                            
                 File: 00-overview.md                                                                                                              
                 File: 01-core-commands.md                                                                                                         
                 File: 02-system-tools.md                                                                                                          
                 File: 03-shell-basics.md                                                                                                          
                 File: 04-posix-and-bash-syntax.md                                                                                                 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                   5 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                               While Loop                                                                
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            ██ POSIX compliant                                               ██ Bash specific                                                      
                                                                                                                                                   
                                                                                                                                                   
                 #!/bin/sh                                                        #!/usr/bin/env bash                                              
                 counter=1                                                        counter=1                                                        
                 while [ $counter -le 5 ]; do                                     while (( counter <= 5 )); do                                     
                     echo "Count $counter"                                            echo "Count $counter"                                        
                     counter=$((counter+1))                                           ((counter++))                                                
                 done                                                             done                                                             
                                                                                                                                                   
                                                                                                                                                   
               ——————————————————— [finished] ———————————————————               ——————————————————— [finished] ———————————————————                 
                                                                                                                                                   
                                                                                                                                                   
                 Count 1                                                          Count 1                                                          
                 Count 2                                                          Count 2                                                          
                 Count 3                                                          Count 3                                                          
                 Count 4                                                          Count 4                                                          
                 Count 5                                                          Count 5                                                          
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                   6 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                           Word Splitting                                                            
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                 files="file1.txt file2.txt file3.txt"                            files="file1.txt file2.txt file3.txt"                            
                                                                                                                                                   
                 # Unquoted: splits into words                                    # Quoted: treated as single string                               
                 for f in $files; do                                              for f in "$files"; do                                            
                     echo "File: $f"                                                  echo "File: $f"                                              
                 done                                                             done                                                             
                                                                                                                                                   
                                                                                                                                                   
               ——————————————————— [finished] ———————————————————               ——————————————————— [finished] ———————————————————                 
                                                                                                                                                   
                                                                                                                                                   
                 File: file1.txt                                                  File: file1.txt file2.txt file3.txt                              
                 File: file2.txt                                                                                                                   
                 File: file3.txt                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            ▍ Again, shellcheck to the rescue :)                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                   7 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                       Playing with Fire: Strings as Code                                        
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            eval takes a string and executes it as a shell command:                   Everything in the string is interpreted,                     
                                                                                      including things you did not intend:                         
                                                                                                                                                   
                      cmd="echo Hello from eval"                                                                                                   
                      eval "$cmd"                                                       # "Creative" user input                                    
                                                                                        ip="127.0.0.1; whoami; hostname"                           
                                                                                        eval "ping -c 1 -q $ip" | tail -3                          
                    ——————————————————— [finished] ———————————————————                                                                             
                                                                                                                                                   
                                                                                      —————————————————— [finished] ——————————————————             
                      Hello from eval                                                                                                              
                                                                                                                                                   
                                                                                        rtt min/avg/max/mdev =                                     
            Imagine a script that asks for an IP address and pings it.                  0.048/0.048/0.048/0.000 ms                                 
                                                                                        runner                                                     
                                                                                        runnervm0hi8g                                              
                      # Intended use                                                                                                               
                      ip="127.0.0.1"                                                                                                               
                      eval "ping -c 1 -q $ip" | tail -3                               ▍ eval is evil!                                              
                                                                                                                                                   
                                                                                         •  Never use eval with user input or any data             
                    ——————————————————— [finished] ———————————————————                      you do not fully control                               
                                                                                         •  In most cases there is a safer alternative             
                                                                                            (arrays, functions, "$@", ...)                         
                    --- 127.0.0.1 ping statistics ---                                                                                              
                    1 packets transmitted, 1 received, 0% packet loss,                                                                             
                    time 0ms                                                                                                                       
                    rtt min/avg/max/mdev = 0.041/0.041/0.Introduction to Linux: Scripting                                                   8 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                           Error Handling                                                            
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            Shell scripts often need strict error handling:                                                                                        
                                                                                                                                                   
                                                                    •  -x : optional: show commands as executed, great for pipelines,              
              #!/usr/bin/env bash                                      debugging, ...                                                              
              set -xeuo pipefail                                       ◦  Uses PS4 environment variable as prompt                                  
                                                                    •  -e : exit immediately on error                                              
                                                                    •  -u : error on unset variables                                               
            This ensures predictable, safe scripts and              •  -o pipefail : pipeline fails if any command in the chain fails              
            easier debugging.                                          ◦  previously existed only in Bash                                          
                                                                       ◦  added in POSIX.1-2024 1                                                  
                                                                                                                                                   
                                                                                                                                                   
            ▍ This could have saved Kyoto University multiple terabytes of valuable research data:                                                 
            ▍ https://www.youtube.com/watch?v=Nkm8BuMc4sQ                                                                                          
            ▍ 6:05 shows why the difference between mv and cp can be very important!                                                               
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                   9 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                          Temporary Files                                                           
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            Scripts often need a place for intermediate results.                •  Creates a file with a unique, unpredictable name                
            mktemp creates one safely:                                             (default in /tmp)                                               
                                                                                •  mktemp -d creates a temporary directory                         
                                                                                •  Never hardcode names like /tmp/myscript.tmp:                    
                 tmp=$(mktemp)                                                     collisions and security issues                                  
                 echo "scratch data" > "$tmp"                                   •  Remember to clean up afterwards, more on that in a              
                 echo "Created $tmp"                                               moment                                                          
                 cat "$tmp"                                                                                                                        
                 rm "$tmp"                                                                                                                         
                                                                                                                                                   
                                                                                                                                                   
               ——————————————————— [finished] ———————————————————                                                                                  
                                                                                                                                                   
                                                                                                                                                   
              Created                                                                                                                              
              /home/runner/work/_temp/nix-shell.0FChq9/tmp.chE3C4oB                                                                                
              s0                                                                                                                                   
              scratch data                                                                                                                         
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                  10 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                Processes and Job Control                                                 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            ██ Key Commands                                                                                                                        
                                                                                                                                                   
            Command │ Description                              │ Example Usage                                                                     
            ────────┼──────────────────────────────────────────┼─────────────────────────────────────                                              
            &       │ Run a command in the background          │ ./long_running_command &                                                          
            Ctrl+Z  │ Pause (suspend) a running process        │ Press Ctrl+Z while running a command                                              
            bg      │ Move a stopped job to the background     │ bg %1 (background job 1)                                                          
            fg      │ Bring a background job to the foreground │ fg %3 (foreground job 3)                                                          
            jobs    │ List all background jobs                 │ jobs                                                                              
                                                                                                                                                   
            ██ Examples                                                                                                                            
                                                                                                                                                   
                                                                                                                                                   
               # Run a command in the background                               # Move the suspended process to the background                      
               $ long_running_task &                                           $ bg                                                                
               [1] 12345  # Job 1, PID 12345                                   [1]+ 12345 long_running_task &                                      
                                                                                                                                                   
               # Suspend the process with Ctrl+Z                               # Bring the process to the foreground                               
               $ ^Z                                                            $ fg                                                                
               [2]+ Stopped              long_running_task                     long_running_task                                                   
                                                                                                                                                   
               # list background jobs                                          # Bring the second background process in the                        
               $ jobs                                                          foreground                                                          
               [1]-  Running                    long_running_task              $ fg %3                                                             
               [2]+  Stopped                    long_running_task              other_task                                                          
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                  11 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                  Signals                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            Signals are small messages the kernel (or other processes) send to a process.                                                          
                                                                                                                                                   
            When you press Ctrl+C or Ctrl+Z, the terminal sends a signal to the running process.                                                   
                                                                                                                                                   
            Signal  │ Nr. │ Typical trigger / use                    │ Default action                                                              
            ────────┼─────┼──────────────────────────────────────────┼────────────────────────────                                                 
            SIGHUP  │ 1   │ Terminal was closed                      │ Terminate                                                                   
            SIGINT  │ 2   │ Ctrl+C                                   │ Terminate                                                                   
            SIGKILL │ 9   │ kill -9 PID                              │ Terminate, cannot be caught                                                 
            SIGTERM │ 15  │ kill PID (default), polite "please quit" │ Terminate                                                                   
            SIGCONT │ 18  │ bg / fg                                  │ Continue a stopped process                                                  
            SIGTSTP │ 20  │ Ctrl+Z (used by job control)             │ Stop (suspend)                                                              
                                                                                                                                                   
            kill lets you send signals to processes via their process ID (PID):                                                                    
                                                                                                                                                   
                                                                                                                                                   
                                      $ kill -l            # list all signals                                                                      
                                      $ kill -TERM 12345   # ask process 12345 to terminate                                                        
                                      $ kill -9 12345      # force kill, process gets no chance to clean up                                        
                                                                                                                                                   
                                                                                                                                                   
            pkill lets you kill processes by name instead of PID: pkill -9 firefox                                                                 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                  12 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                      Cleaning Up on Exit                                                       
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            trap runs a command when the shell receives a signal, so a script can react to e.g., Ctrl+C:                                           
                                                                                                                                                   
                                                                                •  Typical use: remove temporary files, release locks,             
              #!/bin/sh                                                            stop child processes                                            
              tmp=$(mktemp)                                                     •  SIGKILL (and SIGSTOP) cannot be trapped                         
                                                                                •  To restore the default trap behavior, use -:                    
              # EXIT: special pseudo-signal, runs whenever the                     ◦  trap - EXIT or trap - INT                                    
              script ends                                                       •  For complex cleanup procedures, trap a function                 
              trap 'echo "Cleaning up $tmp"; rm -f "$tmp"' EXIT                                                                                    
              # INT: Ctrl+C                                                                                                                        
              trap 'echo "Interrupted!"; exit 130' INT                            cleanup() {                                                      
                                                                                      echo "Clean up"                                              
              echo "working..." > "$tmp"                                              rm -rf "$tmp"                                                
              cat "$tmp"                                                              ...                                                          
                                                                                  }                                                                
                                                                                  trap cleanup EXIT                                                
            —————————————————————— [finished] ———————————————————————                                                                              
                                                                                                                                                   
                                                                                                                                                   
              working...                                                                                                                           
              Cleaning up                                                                                                                          
              /home/runner/work/_temp/nix-shell.0FChq9/tmp.Jk138ZAG                                                                                
              Sc                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                  13 / 14 
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                               Thank you!                                                                
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
            Thank you for your attention!                                                                                                          
                                                                                                                                                   
            Don't forget the feedback in Moodle please!                                                                                            
                                                                                                                                                   
            ▓▓▓ Sources                                                                                                                            
                                                                                                                                                   
            1https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_08_01                                                
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                                                                                                                   
                                                         Introduction to Linux: Scripting                                                  14 / 14