I have an input file that contains only one line:
$ cat input
foo bar
I want to use this line in my script and there are 3 ways to get it that I know of:
line=$(cat input)
line=$(<input)
IFS= read -r line < input
For example, using command substitution means I spawn a subshell, whereas with read
I do not, correct? What other differences are there and is one way preferred over the others? I also noticed (with strace
) that only read
triggers the syscall openat
for some reason. How is it possible that the others don't?
$ strace ./script |& grep input
read(3, "#!/usr/bin/env bash
cat > input"..., 80) = 80
read(255, "#!/usr/bin/env bash
cat > input"..., 167) = 167
read(255, "
line=$(cat input)
line=$(<input"..., 167) = 60
read(255, "line=$(<input)
IFS= read -r line"..., 167) = 41
read(255, "IFS= read -r line < input
", 167) = 26
openat(AT_FDCWD, "input", O_RDONLY) = 3
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…