Zombo
Zombo

Reputation: 1

Bash suppress output from builtin?

Currently I am using a command like this

$ teststring=$(cat foo.txt 2>/dev/null)

This has no output regardless if the file exists, like I want. The following command does not seem to have a way to suppress output, if the file does not exist.

$ teststring=$(<foo.txt)
bash: foo.txt: No such file or directory

Upvotes: 0

Views: 442

Answers (1)

ormaaj
ormaaj

Reputation: 6617

{ teststring=$(<foo.txt); } 2>/dev/null

The simple explanation is expansions are performed before redirections.

The technical explanation is that there is a spec violation in Bash's redirection/assignment order. This special case is an allowable exception, but this isn't an issue in all shells, and the behavior can vary depending upon context. The above workaround should always work regardless.

Upvotes: 2

Related Questions