Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this error mean? (SC2129: Consider using { cmd1; cmd2; } >> file instead of individual redirects.)

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
like image 783
Chris Avatar asked May 12 '15 14:05

Chris


1 Answers

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
like image 192
fedorqui 'SO stop harming' Avatar answered Sep 21 '22 07:09

fedorqui 'SO stop harming'