# Shell Coding Guidelines

Prefer portable POSIX `sh` idioms unless a tool-specific feature (e.g., GNU `parallel`, GNU `dd`) is explicitly needed.

## String Manipulation (POSIX)

Strip everything after the first or last occurrence of `$separator`:

```sh
result="${string%%"$separator"*}"  # Before first occurrence ('abc-def-ghi' -> 'abc')
result="${string%"$separator"*}"   # Before last occurrence  ('abc-def-ghi' -> 'abc-def')
```

## Pipelines and Safe File Handling

- **Group commands in the current shell** (no unnecessary subshells; requires a space after `{` and trailing `;` before `}`):
  ```sh
  { cat file.txt; echo 'additional content'; } | your_next_command
  ```
- **Handle arbitrary filenames** (spaces, newlines, quotes) with NUL-delimited `find` + `xargs`:
  ```sh
  find mydir -name '*.txt' -print0 | xargs -0 rm
  ```
- **Stream copies / pseudo-files** (`/proc`, `/sys`, or live progress via GNU `dd` when `cp` is unsuitable):
  ```sh
  cat sourcefile | dd of=destinationfile status=progress
  ```

## Concurrency with GNU Parallel

`parallel` runs jobs across cores, waits for completion, propagates `Ctrl+C`/`SIGTERM` to children, and buffers each job's output by default:

```bash
parallel ::: cmd1 cmd2 cmd3                          # Basic parallel run (buffered)
parallel --ungroup --ungroup ::: cmd1 cmd2 cmd3      # Stream stdout/stderr immediately
parallel -j 2 --halt soon,fail=1 ::: cmd1 cmd2 cmd3  # Cap at 2 jobs; stop on first failure
parallel bash -c ::: "cmd1 | pipe" "for f in *.txt; do echo \$f; done"
ls *.biginput | parallel 'step --input {} --output {}.out'
```

## Batch Killing Processes

Filter out the `grep` process itself, extract PIDs (`$2`), and signal them:

```sh
for pid in $(ps aux | grep <pattern> | grep -v grep | awk '{print $2}'); do
    kill -15 "$pid"
done
```

## Parsing Options with POSIX `getopts`

- Single-character options (`-a`, `-c foo`, `-cfoo`); chainable (`-ab`, `-abc foo`) if earlier options take no arguments.
- Prefix `optstring` with `:` to handle missing arguments silently; append `:` after options that take an argument (e.g., `:abc:d:`):
  - Valid option: `name` is the option letter; argument value (if any) is in `$OPTARG`.
  - Missing argument: `name=":"`, `OPTARG` is the option letter.
  - Invalid option: `name="?"`, `OPTARG` is the option letter.

```sh
#!/bin/sh
while getopts ':abc:d:' name; do
    case $name in
        a|b) echo "Option -$name" ;;
        c|d) echo "Option -$name with argument $OPTARG" ;;
        :)   echo "Option -$OPTARG requires an argument" ;;
        ?)   echo "Invalid option -$OPTARG" ;;
    esac
done
```

## References

- https://www.baeldung.com/linux/grep-exclude-ps-results
- https://stackoverflow.com/questions/46008880/how-to-always-cut-the-pid-from-ps-aux-command
- https://en.wikipedia.org/wiki/Getopts
- https://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
- https://en.wikipedia.org/wiki/Getopt
- https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
