18

I'm writing a script to generate draft posts for my blog. After running ShellCheck, I keep seeing this error pop up. What does this mean and can someone provide an example?

SC2129: Consider using { cmd1; cmd2; } >> file instead of individual redirects.

In addition, I'm not sure what I need to do in order to pass the value of $title to the "Title" field in the post's YAML...

#!/bin/bash

# Set some variables

var site_path=~/Documents/Blog
drafts_path=~/Documents/Blog/_drafts
title="$title"

# Create the filename

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

# Create the file, Add metadata fields

echo "---" > "$file_path"
{
    echo "title: \"$title\""
}   >> "$file_path"

echo "layout: post" >> "$file_path"
echo "tags: " >> "$file_path"
echo "---" >> "$file_path"

# Open the file in BBEdit

bbedit "$file_path"

exit 0
Will
  • 24,082
  • 14
  • 97
  • 108
Chris
  • 547
  • 6
  • 20
  • 2
    `{echo 'foo'; echo 'bar'; echo 'baz'; } >> file` instead of separate/repeated `echo x >> file` – Marc B May 12 '15 at 15:00

1 Answers1

31

If you click in the message given by shellcheck, you will arrive to https://github.com/koalaman/shellcheck/wiki/SC2129

There you can find the following:

Problematic code:

echo foo >> file
date >> file
cat stuff  >> file

Correct code:

{ 
  echo foo
  date
  cat stuff
} >> file

Rationale:

Rather than adding >> something after every single line, you can simply group the relevant commands and redirect the group.

Exceptions

This is mainly a stylistic issue, and can freely be ignored.

So basically replace:

echo "---" > "$file_path"
{
    echo "title: \"$title\""
}   >> "$file_path"

echo "layout: post" >> "$file_path"
echo "tags: " >> "$file_path"
echo "---" >> "$file_path"

With:

{
    echo "---"
    echo "title: \"$title\""
    echo "layout: post"
    echo "tags: "
    echo "---"
}   > "$file_path"

Even though I would suggest you to use a heredoc:

cat >"$file_path" <<EOL
---
title: "$title"
layout: post
tags: 
---
EOL
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 4
    The first version opens and closes the file several times. The second opens and closes it just once. It doesn't matter much, but it's something to consider. – Keith Thompson Jan 24 '16 at 02:08