2

I have a script I use to create draft blog posts as I work on them. Recently, I added two fields for post excerpts and tags. However, I get an unbound variable error when I try to run it. Niether bash -n or shellcheck catches this and I assumed set -u would resolve this internally, but I guess not.

How should this be handled?

#!/bin/bash

set -eu

# Set some variables

export site_path=~/Documents/Blog
drafts_path=~/Documents/Blog/_drafts
title="$1"

# Create the filename

title=$(awk '{print tolower($0)}' <<<"$title")
filename="$title.markdown"
file_path="$drafts_path/$filename"
echo "File path: $file_path"

# Create the file, Add metadata fields

cat >"$file_path" <<EOL
---
title: "$title"
layout: post
excerpt:
tags: []
---
EOL

# Open the file in BBEdit

bbedit "$file_path"

exit 0
Chris
  • 547
  • 6
  • 20
  • 1
    You should get the line where the error is like `./test.sh: line 9: $1: unbound variable`. Did you pass the title to the script? Like `./test.sh title` (first parameter) – shadowsheep Mar 01 '18 at 16:02
  • `set -u` doesn't resolve anything; it is what is producing the unbound variable error. Without it, an unbound variable simply expands to the empty string. If you are going to use `set -u`, take advantage of the error it provides and find out which variable isn't set, then ensure that it *gets* set. – chepner Mar 01 '18 at 16:11
  • @shadowsheep Yeah, just realized I did set this up so I could do `script/draft title` and after reverting locally, that works. Although, I wonder if it is possible to *also* do it without any arguments... A conditional `else` perhaps? – Chris Mar 01 '18 at 16:20
  • 1
    Yep, and if statement should do the trick. Check it out: https://stackoverflow.com/questions/6482377/check-existence-of-input-argument-in-a-bash-shell-script – shadowsheep Mar 01 '18 at 16:23
  • Answered by the technique used for [this question](https://stackoverflow.com/questions/6482377/check-existence-of-input-argument-in-a-bash-shell-script). – Chris Mar 01 '18 at 16:34

0 Answers0