cat $file 2>/dev/null and <$file 2>/dev/null are not equivalent if file does not exist
For bugs
- Rule Id (if any, e.g. SC1000): SC2002
- My shellcheck version (
shellcheck --versionor "online"): 0.9.0 - [ x] The rule's wiki page does not already cover this (e.g. https://shellcheck.net/wiki/SC2086)
- [x ] I tried on https://www.shellcheck.net/ and verified that this is still a problem on the latest commit
For new checks and feature suggestions
- [ x] https://www.shellcheck.net/ (i.e. the latest commit) currently gives no useful warnings about this
- [x ] I searched through https://github.com/koalaman/shellcheck/issues and didn't find anything related
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
-
trdoes not accept a file name argument; so thecmd "${file}"is not possible -
cat "${file}" 2>/dev/nulland<"${file}" 2>/dev/nullare not equivalent; the former does not output an errormessage when the file does not exist, whilst the latter does because it's the shell complaining, not an external tool.
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
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.
"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: @.***>
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).