0

I need to build a string of --build-arg parameter using some key/value pairs (build.args file) in a busybox shell:

script.sh

#!/bin/sh
one=$1
two=$2
shift

while IFS= read -r line; do
    set "$@" --build-arg "$line"
done < "build.args"

echo "$@"

build.args

ONE=first
TWO=second

Running sh script.sh foo bar (yes, two parameters are needed for the script) should read the content of build.args and add the key/value pairs as --build-arg parameter and output this generated string. This is what I am expecting:

--build-arg ONE=first --build-arg TWO=second

But with my script I do get

bar --build-arg ONE=first --build-arg TWO=second

as bar is passed as second parameter in the script call.

1 Answer 1

4

You are getting bar in there because that's what $1 is after your shift operation before the loop.

To shift off two positional parameters, use shift 2. However, it may be safer to clear the list of positional parameters before the loop by replacing shift with set --. That way, you don't rely on the user supplying the correct number of parameters. Some shells would issue a diagnostic message if you tried to shift off more values than in the list, and if the user gives you too few or too many values, these would still be in "$@".

Also, you will need to use set -- in place of plain set when setting positional parameters, both in this case and in general, to avoid accidentally setting shell options or, as in this case, invoking set with invalid options.

set -- "$@" --build-arg "$line"
2
  • It's not only in general that you need the --. It applies to this specific case. busybox sh -c 'set --build-arg' errors out with sh: set: line 1: illegal option --; shift "$#" is an other way to empty "$@". That and doing set x ${1+"$@"} more; shift was what you had to do with some shells that didn't support set -- nor set - in the olden days IIRC. Commented Oct 4, 2021 at 6:30
  • @StéphaneChazelas Sorry, I might have used the phrase "in general" to mean "always" (including any specific case). In any case, I will update that sentence. Thanks. Commented Oct 4, 2021 at 6:33

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.