From ab7c6cfa61f7a72358aabd031f2ad1849915b706 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Wed, 30 Dec 2020 19:39:25 -0800 Subject: [PATCH] Created SC2270 (markdown) --- SC2270.md | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 SC2270.md diff --git a/SC2270.md b/SC2270.md new file mode 100644 index 0000000..9b6a784 --- /dev/null +++ b/SC2270.md @@ -0,0 +1,52 @@ +## To assign positional parameters, use 'set -- first second ..' (or use [ ] to compare). + +### Problematic code: + +```sh +if [ -z "$1" ] +then + $1="help" +fi +``` + +or + +```sh +if $1="help" +then + echo "Usage: $0 filename" +fi +``` + +### Correct code: + +```sh +if [ -z "$1" ] +then + set -- "help" +fi +``` + +or + +```sh +if [ $1 = "help" ] +then + echo "Usage: $0 filename" +fi +``` +### Rationale: + +You have a command on the form `$2=value`. + +If the goal is to assign a new value to the positional parameters, use the `set` builtin: `set -- one two ..` will cause `$1` to be "one" and `$2` to be "two". + +If you instead want to compare the value, use `[ ]` and add spaces: `[ "$1" = "foo" ]` + +### Exceptions: + +None + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file