0

My goal is to make a shell script that I can run that will generate a static HTML page and I would like to change some of the data in the file, like some text or a class name and I would like to get those variables from a command line argument, like this:

sh createfile.sh --title "Example" --author "Example"

Can you even handle command arguments with a shell script?

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    Yes, of course you can handle command line arguments. But for your use case, it might be easier to just do `title=Example author=Example sh createfile.sh`. (Assuming you're not using a shell from the `csh` family). That will make `$title` and `$author` available in the script. – William Pursell Jun 02 '21 at 14:59
  • getopts is another option that can be used – abhishek phukan Jun 02 '21 at 15:05

1 Answers1

0

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.

William Pursell
  • 204,365
  • 48
  • 270
  • 300