From 6666e556a43198f0a7977fbb4d26e4fa3921cc63 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 1 Mar 2014 14:41:30 -0800 Subject: [PATCH] Created SC2120 (markdown) --- SC2120.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 SC2120.md diff --git a/SC2120.md b/SC2120.md new file mode 100644 index 0000000..20f419d --- /dev/null +++ b/SC2120.md @@ -0,0 +1,35 @@ +# foo references arguments, but none are ever passed. + +### Problematic code: + + sayhello() { + echo "Hello $1" + } + sayhello + +`./myscript World` just prints "Hello " instead of "Hello World". + +### Correct code: + + sayhello() { + echo "Hello $1" + } + sayhello "$@" + +`./myscript World` now prints "Hello World". + +### Rationale: + +In a function, `$1` and up refers to the function's parameters, not the script's parameters. + +If you want to process your script's parameters in a function, you have to explicitly pass them. You can do this with `myfunction "$@"`. + +Note that `"$@"` refers to the current context's positional parameters, so if you call a function from a function, you have to pass in `"$@"` to both of them: + + first() { second "$@"; } + second() { echo "The first script parameter is: $1"; } + first "$@" + +### Contraindications + +If the parameters are optional and you currently just don't want to use them, you can ignore this message.