0

Consider the following case:

$ echo "abc" > file
$ var=$(< file)
$ echo "$var"
abc

Inside the command substitution, we use a redirect and a file, and the content of the file is correctly captured by the variable.

However, all the following examples produce no output:

$ < file
$ < file | cat
$ < file > file2
$ cat file2

In all these cases the content of the command is not redirected to the output.

So why is there a difference when the redirect is placed inside the command substitution or not? Does the redirect have a different function when inside vs outside a command substitution block?

user000001
  • 32,226
  • 12
  • 81
  • 108
  • 1
    You should be using `cat – anubhava Oct 22 '16 at 16:11
  • 2
    @anubhava: That's true. Or even `cat file`. The thing I don't understand though is the reason behind the different syntax. Why does `$( – user000001 Oct 22 '16 at 16:13
  • 1
  • @anubhava: I see, so the `< file` syntax is only valid inside the command substitution. I thought that the command inside or outside would follow the same rules. – user000001 Oct 22 '16 at 16:23
  • try `< file wc` or `< file grep -o 'b'` – Sundeep Oct 22 '16 at 16:52
  • 1
    @Sundeep: Both of these examples work. But the difference is that they involve executing a command, whereas in `$( < file )` the redirect works even with no command. – user000001 Oct 22 '16 at 16:55
  • I think that is how redirection works outside of substitution.. it needs a command which can accept it as stdin – Sundeep Oct 22 '16 at 17:00
  • 1
    Technically, `$(< file)` is not a redirection; it's a special case of command substitution that *looks* like a redirection. – chepner Oct 22 '16 at 17:24
  • @chepner: I think your comment qualifies as an answer... So basically if I understand correctly, you are saying that since it is not really a redirect, but a special case of command substitution, we should not expect the syntax to work anywhere a command is expected. – user000001 Oct 22 '16 at 17:29

1 Answers1

3

$(< file) is not a redirection; it is just a special case of a command substitution that uses the same syntax as an input redirection.

In general, an input redirection must be associated with a command. There is one case that arguably could be considered an exception, which is

$ > file

It's not technically a redirection, since nothing is redirected to the file, but file is still opened in write mode, which truncates it to 0 bytes.

chepner
  • 497,756
  • 71
  • 530
  • 681