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

旧街凉风 提交于 2019-12-10 13:06:04

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/30194596/what-does-this-error-mean-sc2129-consider-using-cmd1-cmd2-file-inste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!