shellcheck 警告 SC2129「考慮使用 { cmd1; cmd2; } >> 檔案而不是單獨的重定向。意思是?

shellcheck 警告 SC2129「考慮使用 { cmd1; cmd2; } >> 檔案而不是單獨的重定向。意思是?

我有這個shellcheck警告,我無法弄清楚:

In /mnt/e/bin/iconic line 540:
            printf "FALSE|" >> "$IconsRaw"           # Select field number 1
            ^-- SC2129: Consider using { cmd1; cmd2; } >> file instead of individual redirects.

我注意到我們這裡很多人都使用外殼檢查修復我們的 bash 腳本/shell 命令,所以我希望問題是主題。


根據發布 bash 腳本相關部分的評論:

    if [[ "$X" == "?" || "$Y" == "?" ]] ; then
        : # Bad X or Y offset usually "Link to Name.ext~" (backup name)
    else
        let i++
        printf "FALSE|" >> "$IconsRaw"           # Select field number 1
        printf "%s|" "$i" >> "$IconsRaw"         # 2
        printf "%s|" "${File##*/}" >> "$IconsRaw"
        printf "%s|" "$Linkless" >> "$IconsRaw"  # 4
        printf "%s|" "$Date" >> "$IconsRaw"      # 5
        printf "%s|" "$X" >> "$IconsRaw"         # 6
        echo   "$Y" >> "$IconsRaw"               # 7
    fi

解決方案

感謝接受的答案和評論,我了解到它shellcheck不僅可以捕獲程式碼中的錯誤,還可以建議效能改進。在這種情況下,檔案名稱被每個和$IconsRaw多次開啟和關閉。printfecho

更有效率的 bash 程式碼:

    # X,Y screen coordinates invalid on backup files ending with "~"
    ! [[ "$X" == "?" || "$Y" == "?" ]] && { let i++; echo \
        "FALSE|$i|${File##*/}|$Linkless|$Date|$X|$Y" >> "$IconsRaw"; }

答案1

我假設您的腳本有多個>> "$IconsRaw".該訊息建議僅重定向輸出一次並將命令分組到子 shell 中。大概是為了避免多次開啟和關閉檔案的開銷。

所以,而不是這個:

    printf "FALSE|" >> "$IconsRaw"           # Select field number 1
    printf "%s|" "$i" >> "$IconsRaw"         # 2
    printf "%s|" "${File##*/}" >> "$IconsRaw"
    printf "%s|" "$Linkless" >> "$IconsRaw"  # 4
    printf "%s|" "$Date" >> "$IconsRaw"      # 5
    printf "%s|" "$X" >> "$IconsRaw"         # 6
    echo   "$Y" >> "$IconsRaw"               # 7

這:

{
    printf "FALSE|"            # Select field number 1
    printf "%s|" "$i"          # 2
    printf "%s|" "${File##*/}" 
    printf "%s|" "$Linkless"   # 4
    printf "%s|" "$Date"       # 5
    printf "%s|" "$X"          # 6
    printf "%s\n" "$Y"         # 7
} >> "$IconsRaw"

但這也是不必要的重複printf,而且這樣做會更有效:

printf '%s|%s|%s|%s|%s|%s|%s\n' \
      'FALSE' "$i" "${File##*/}" "$Linkless" \
      "$Date" "$X" "$Y" >> "$IconsRaw"

相關內容