1

I'm making a page generator in bash. When checking for argument $2 to use as title of the page i'm generating, it finds nothing and echo the "No title supplied..." line.

Here is the snippet containing $2:

header() {
echo "<!DOCTYPE html>" > $filename.html
echo "<html>" >> $filename.html
echo "<head>" >> $filename.html
if [ -z "$2" ]; then
    echo "No title supplied. Using name of the file."
    echo "  <title>$filename</title>" >> $filename.html
else
    echo "  <title>$2</title>" >> $filename.html
fi
echo "  <link rel=\"stylesheet\" href=\"styles.css\">" >> $filename.html
echo "</head>" >> $filename.html
echo "<body>" >> $filename.html
echo "" >> $filename.html
}

Here is the link to the full script: https://ghostbin.co/paste/p8qpx

3
  • 1
    Neither call to header is given any arguments, let alone a 2nd argument. The function cannot see the script's positional arguments, if that is what you are referring to. Commented Apr 21, 2020 at 14:42
  • 1
    As an aside, I'd recommend a command group to avoid having to constantly (re)open $filename.html: { echo ...; echo ...; ...; } > $filename.html. The "no title supplied" line should be written to standard error (echo "No title..." >&2). Commented Apr 21, 2020 at 14:44
  • Thanks for the tips. I'm new to this. Commented Apr 21, 2020 at 14:45

1 Answer 1

2

Inside a function, $2 refers to the second argument of that function, not of the whole script. So you have to pass that as a parameter when calling header

Like this

header "$2"

Then, inside your function, it will be $1 since it will be the first parameter of that function call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.