Bash – What does the expression $(<“dir/file”) mean in bash

bashcommand-substitutionio-redirectionshell

In a bash script I cannot post here I see the following expression:

$(<"dir/file")

From what I understand the expression $(...) evaluates a command inside (as when using backticks), but what is the role of the angle bracket used inside the round bracket?

Best Answer

A redirection <"dir/file" opens the file for reading on standard input for the duration of the command that the redirection applies to. When there is no command, the file is open for reading (which leads to an error if the file doesn't exist or lacks proper permission), but other than that the redirection has no effect.

Ksh added an extension, which has been adopted by bash and ksh. If a command substitution contains an input redirection and nothing else $(<"dir/file") (no command, no other redirection, no assignment, etc.), then the command susbtitution is replaced by the content of the file. Thus $(<"dir/file") is equivalent to $(cat "dir/file") (except that it doesn't call the cat utility, so it's marginally faster and does the same thing even if cat has been replaced or isn't in the command search path).

This is mentioned in the bash manual under “command substitution”.

Related Question