From af648d27f19c5cd0ae873c873618829a0ea1d4e9 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Tue, 1 Sep 2020 17:05:12 -0700 Subject: [PATCH] Created SC3001 (markdown) --- SC3001.md | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 SC3001.md diff --git a/SC3001.md b/SC3001.md new file mode 100644 index 0000000..cfb7008 --- /dev/null +++ b/SC3001.md @@ -0,0 +1,56 @@ +## In POSIX sh, process substitution is undefined. + +(or "In dash, ... is not supported." when using `dash`) + +### Problematic code: + +```sh +#!/bin/sh +while IFS= read -r n +do + sum=$((sum+n)) +done < <(program) +``` + +### Correct code: + +The easiest fix is to switch to a shell that does support process substitution, by changing the shebang to `#!/bin/bash` or `ksh`. + +```sh +#!/bin/bash +while IFS= read -r n +do + sum=$((sum+n)) +done < <(program) +``` + +Alternatively, process substitution can often be replaced with temporary files: + +```sh +#!/bin/sh +tmp="$(mktemp)" +program > "$tmp" +while IFS= read -r n +do + sum=$((sum+n)) +done < "$tmp" +rm "$tmp" +``` + +If streaming is important, the temporary file can be a named pipe, and the producer or consumer can be run as a background job. + +### Rationale: + +Process substitution is a ksh and bash extension. It does not work in sh or dash scripts. + +### Exceptions: + +If you only intend to target shells that supports this feature, you can change +the shebang to a shell that guarantees support, or [[ignore]] this warning. + +You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility +warnings. + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!