【发布时间】:2019-01-26 23:51:28
【问题描述】:
我有一个只包含一行的输入文件:
$ cat input
foo bar
我想在我的脚本中使用这一行,我知道有 3 种方法可以得到它:
line=$(cat input)
line=$(<input)
IFS= read -r line < input
例如,使用命令替换意味着我生成一个子shell,而使用read 我没有,对吗?还有哪些其他差异,一种方式优于其他方式?我还注意到(使用strace)只有read 出于某种原因触发了系统调用openat。别人怎么可能不呢?
$ strace ./script |& grep input
read(3, "#!/usr/bin/env bash\n\ncat > input"..., 80) = 80
read(255, "#!/usr/bin/env bash\n\ncat > input"..., 167) = 167
read(255, "\nline=$(cat input)\nline=$(<input"..., 167) = 60
read(255, "line=$(<input)\nIFS= read -r line"..., 167) = 41
read(255, "IFS= read -r line < input\n", 167) = 26
openat(AT_FDCWD, "input", O_RDONLY) = 3
【问题讨论】:
-
"只有
read出于某种原因触发了系统调用 openat。其他人怎么可能不这样做?" -- 如您所知,第一个两个命令在子 shell 中读取文件。确保您要求strace也跟踪由您跟踪的初始进程产生的子进程。