gpt4 book ai didi

bash - 一行文件的 "$(cat file)"、 "$(
转载 作者:行者123 更新时间:2023-11-29 08:54:51 28 4
gpt4 key购买 nike

我有一个只包含一行的输入文件:

$ 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

最佳答案

  • line=$(cat input)是读取整个文件的 POSIX 方式。它需要一个 fork 。

  • line=$(< input)是一种稍微更有效的 Bashism,用于读取整个文件。它还会 fork ,但不必执行。

  • 未提及但 mapfile/readarray对于将整个文件逐行读取到数组中,Bashisms 的效率要高得多。没有 fork 。

  • IFS= read -r line < input是在没有子 shell 的情况下读取单行的 POSIX 方式。没有 fork 。

你只看到后者打开文件的原因很简单,其他人是在子shell中做的,而你没有指定-f。跟踪子进程。

关于bash - 一行文件的 "$(cat file)"、 "$(<file)"和 "read ... < file"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51937702/

28 4 0

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com