首页 > 解决方案 > Why does redirection in `< /dev/urandom tr | tr` work; how does this parse?

问题描述

I use this to make passwords:

echo $(LC_CTYPE=C < /dev/urandom tr -cd [:graph:] | tr -d '\n' | head -c32) # pwg ##1st

Varying length, graph to alnum, or whatever.

I don't understand the redirection being used. I understand the outer $() format but this

echo $(LC_CTYPE=C < /dev/urandom tr -cd [:graph:] ...

doesn't make sense.

To me it seems it should be:

echo $(LC_CTYPE=C tr -cd [:graph:] < /dev/urandom | tr -d '\n' | head -c32) # pwg ##2nd

Which also works. I just can't understand why the first variant works?

标签: bashshell

解决方案


手册中的一些信息:

3.6 重定向

在执行命令之前,它的输入和输出可能会使用由 shell 解释的特殊符号重定向... 以下重定向运算符可能出现在简单命令的任何位置之前或出现在命令之后。...

3.7.1 简单的命令扩展

执行简单命令时,shell 从左到右执行以下扩展、赋值和重定向。

  1. 解析器标记为变量赋值(命令名前面的那些)和重定向的词被保存以供以后处理
  2. 不是变量赋值或重定向的词被扩展(参见 Shell 扩展)。如果展开后还剩下任何单词,则将第一个单词作为命令的名称,其余单词作为参数。
  3. 如上所述执行重定向(请参阅重定向)。
  4. 在分配给变量之前,每个变量赋值中“=”之后的文本都经过波浪号扩展、参数扩展、命令替换、算术扩展和引号删除。

推荐阅读