From 44b7c2cbf885969fcc98f34fa0bf7418dadf3e54 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Tue, 1 Sep 2020 17:34:25 -0700 Subject: [PATCH] Updated SC3053 (markdown) --- SC3053.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/SC3053.md b/SC3053.md index eb8e505..2be8b29 100644 --- a/SC3053.md +++ b/SC3053.md @@ -1,36 +1,36 @@ -## In POSIX sh, array references are undefined. +## In POSIX sh, indirect expansion is undefined. -(or "In dash, ... are not supported." when using `dash`) +(or "In dash, ... is not supported." when using `dash`) ### Problematic code: ```sh #!/bin/sh -var=(foo bar) -echo "${var[1]}" +name="PATH" +echo "${!name}" ``` ### Correct code: -The easiest solution is to switch to a shell that does support arrays, like `bash`: +The easiest solution is to switch to a shell that does support indirect expansion, like `bash`: ```sh #!/bin/bash -var=(foo bar) -echo "${var[1]}" +name="PATH" +echo "${!name}" ``` -Alternatively, rewrite the logic to use e.g. indirect variable references or `set`: +Alternatively, carefully rewrite using `eval`: ```sh #!/bin/sh -set -- foo bar -echo "$2" +name=PATH +eval "echo \"\$$name\"" ``` ### Rationale: -Arrays are supported in `bash` and `ksh`, but not in `dash` or POSIX `sh`. Either switch to a shell that supports them, or rewrite your script without relying on arrays. This may not be straight forward. +Indirection expansion is an extension in `bash` and `ksh`, and not supported in `dash` or POSIX `sh`. Either switch to a shell that supports them, or write around it with careful use of `eval`. Take care to validate the variable name to avoid fragility and code injection. ### Exceptions: