Skip to main content
czerasz.com: notes
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Bash

  • Initialisation section:

    1
    2
    3
    4
    5
    6
    
    #!/usr/bin/env bash
    
    set -eu -o pipefail
    
    script_directory="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    project_directory="${script_directory}/.."
    
  • Execute command for each line:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    #!/usr/bin/env bash
    
    while read -r line; do
      # skip empty lines
      if [ -z "$line" ]; then
        continue
      fi
      echo "- ${line}"
    done < <(find . -type d -name node_modules)
    

    Can be also used with done < input.out

  • Loop through array items:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
    #!/usr/bin/env bash
    files=(
      "/etc/passwd"
      "/etc/group"
      "/etc/hosts"
    )
    
    for i in "${files[@]}"; do
      echo "- ${i}"
    done
    
  • named pipes

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    #!/usr/bin/env bash
    
    # remove previous named pipe
    rm -f pipe || true
    
    # create a named pipe
    mknod pipe p
    
    # open a file for reading and writing
    # save it's file descriptor to variable $fd
    exec {fd}<>pipe
    
    client() {
      local name=$1
    
      while true; do
        sleep 3
        echo "[client ${name}] hi" >&$fd
      done
    }
    
    client one &
    client two &
    client three &
    
    while read -r -u "$fd" line; do
      echo "[read line] ${line}"
    done