Try this script as a base, expanding / modifiying it for your own parameters:
#!/bin/bash
config=()
outfile=default-outfile.cfg
while [[ $# -gt 0 ]]
do
case "$1" in
-a|--alpha)
config+=(alpha "$2")
shift 2
;;
-b|--beta)
config+=(beta "$2")
shift 2
;;
-o)
outfile="$2"
shift 2
;;
*)
echo >&2 "Error parsing arguments: unknown option $1"
exit 1
esac
done
printf '%s = %s\n' "${config[@]}" > "$outfile"
The while
loops over all command line arguments, and from them creates an array like
config=(alpha 2 beta 3)
i.e. the keys and values are interleaved - a key followed by a value, followed by the next pair.
It is then trivial to print them out into a config file with the printf
call.
printf '%s = %s\n'
consumes a set of two arguments (let's call them $1 and $2), and outputs $1 = $2
(followed by a newline). If there are more than two arguments present, it will do this in a loop until all arguments were consumed. Its output is redirected by the shell into the file named by $outfile
The final printf command in this example as invoked by the shell would therefore be
printf '%s = %s\n' "alpha" "2" "beta" "3"
and result in the output
alpha = 2
beta = 3
More examples:
$ ./script.sh --alpha 2 -b 5
$ cat default-outfile.cfg
alpha = 2
beta = 5
$ ./script.sh --alpha omega --yankee doodledandy
Error parsing arguments: unknown option --yankee
$ cat default-outfile.cfg
alpha = 2
beta = 5
$ # (unchanged, as there was an error)
$ ./script.sh -a omega -o otherfile.cfg
$ cat otherfile.cfg
alpha = omega
$
Please do note that due to platform-specific restrictions, it may be impossible to call printf with many arguments, however it is unlikely that you'll run into this kind of error unless your users use very (very very!) long filenames or many options, and it is unlikely that the call to your script succeeded in that case in the first place.
printf 'alpha = 2\nbeta = 3\n' >config.cfg
. Could you explain why you need a script for this? – Kusalananda♦ Nov 4 '18 at 18:04alpha
andbeta
? Are the values of the parameters always positive integers, or could it be strings as well (with embedded spaces, tabs and/or newlines)? Does the script need to do any validation of the given parameters and their values so that only valid data is written to the configuration file? – Kusalananda♦ Nov 4 '18 at 18:23