koalaman / shellcheck

ShellCheck, a static analysis tool for shell scripts
https://www.shellcheck.net
GNU General Public License v3.0
36.45k stars 1.78k forks source link

cat $file 2>/dev/null and <$file 2>/dev/null are not equivalent if file does not exist #2887

Open KaspervdHeijden opened 11 months ago

KaspervdHeijden commented 11 months ago

For bugs

For new checks and feature suggestions

Here's a snippet or screenshot that shows the problem:

#!/urs/bin/env sh

file="somefile.txt"

cat "${file}" 2>/dev/null | tr '\n' ' '

Here's what shellcheck currently says:

cat "${file}" 2>/dev/null | tr '\n' ' ' ^-- SC2002 (style): Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead.

Here's what I wanted or expected to see:

Nothing

slycordinator commented 10 months ago

You can suppress the output of <"${file}" for a non-existent file.

Depending on your needs, you could use: { <"${file}"; } 2>/dev/null or ( <"${file}"; ) 2>/dev/null

KaspervdHeijden commented 10 months ago

Nice trick! Today I learned. Would it be possible to let shellcheck suggest this in this specific situation?

For what it's worth, I guess we're now in the territory that it's just easier to use cat anyway, making it a false positive (we are still creating a subshell). But that's just my option.

slycordinator commented 10 months ago

"we are still creating a subshell"

The option with {} doesn't create a stubshell.

On Fri, Dec 29, 2023, 7:18 PM Kasper van der Heijden < @.***> wrote:

Nice trick! Today I learned. Would it be possible to let shellcheck suggest this in this specific situation?

For what it's worth, I guess we're now in the territory that it's just easier to use cat anyway, making it a false positive (we are still creating a subshell). But that's just my option.

— Reply to this email directly, view it on GitHub https://github.com/koalaman/shellcheck/issues/2887#issuecomment-1871923844, or unsubscribe https://github.com/notifications/unsubscribe-auth/AQN7DTPY5US4K6LGLPTTHT3YL2KINAVCNFSM6AAAAABA4WEHPGVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQNZRHEZDGOBUGQ . You are receiving this because you commented.Message ID: @.***>

KaspervdHeijden commented 10 months ago

Note: If I use { <"${file}"; } 2>/dev/null shellcheck still does not like it:

^-- SC2188 (warning): This redirection doesn't have a command. Move to its command (or use 'true' as no-op).