There are a lot of ways to parse command line arguments in a script. The most basic is just to reference them via $1
, $2
, etc. But for your use case, it's probably easier to not bother. Just do something like:
$ cat createfile.sh
#!/bin/sh
cat << EOF
${title?}
Written by ${author?}
EOF
$ author=doug title='my document' sh createfile.sh
my document
Written by doug
There certainly are reasons to avoid using the environment this way, but if you want to pass the value as parameters there's no reason to enforce using --
as an indicator. Just do:
#!/bin/sh
for x; do
if ! test "$x" = "${x#*=}"; then
eval "$x"
fi
done
cat << EOF
${title?}
Written by ${author?}
EOF
$ sh createfile.sh author=foo title=bar
bar
Written by foo
By avoiding the environment, you prevent accidentally grabbing unexpected values. Also, this will work if you are using one of the shells from the csh
family. This is certainly not robust, and any use of eval
is suspect, but these are 2 reasonably useful techniques.