如何使用 bash 脚本和 for 循环回显文件行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13298255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:56:05  来源:igfitidea点击:

How to echo lines of file using bash script and for loop

bash

提问by ChickenFur

I have a simple file called dbs.txt I want to echo the lines of that file to the screen using a for loop in bash.

我有一个名为 dbs.txt 的简单文件,我想使用 bash 中的 for 循环将该文件的行回显到屏幕上。

The file looks like this:

该文件如下所示:

db1
db2
db3
db4

The bash file is called test.sh it looks like this

bash 文件被称为 test.sh 它看起来像这样

for i in 'cat dbs.txt'; do
echo $i
done
wait

When I run the file by typing:

当我通过键入运行文件时:

bash test.sh

I get the terminal output:

我得到终端输出:

cat dbs.txt

instead of the hoped for

而不是所希望的

db1
db2
db3
db4

The following bash file works great:

以下 bash 文件效果很好:

cat dbs.txt | while read line
do
echo "$line"
done

Why doesn't the first script work?

为什么第一个脚本不起作用?

回答by Todor

You can use the shell builtin readinstead of cat. If you process just a single file and it's not huge, perhaps the following is easier and more portable than most solutions:

您可以使用内置的 shellread而不是cat. 如果您只处理一个文件并且它不是很大,那么以下方法可能比大多数解决方案更容易和更便携:

#!/bin/sh

while read line
do
    printf "%s\n" "$line"
done < ""

I remember reading somewhere that printfis safer than echoin the sense that the options that echoaccepts may differ across platforms. So building a habit of using printfmay be worthwhile.

我记得在某处阅读printf比接受echo的选项echo可能因平台不同而更安全的地方。所以养成使用习惯printf可能是值得的。

For description of the readbuiltin, check the manual pages of your shell.

有关read内置的说明,请查看您的 shell 的手册页。

回答by Linus Gustav Larsson Thiel

You need to execute a sub-shell and capture the output, like this:

您需要执行一个子 shell 并捕获输出,如下所示:

for i in `cat dbs.txt`; do
echo $i
done
wait

Note the backticks ` instead of the single-quotes.

注意反引号 ` 而不是单引号。

In bash you can also use $(command):

在 bash 中,您还可以使用$(command)

for i in $(cat dbs.txt); do
echo $i
done
wait

回答by Gilles Quenot

You need command substitutionshell feature. This require the POSIXexpression $().

您需要命令替换shell 功能。这需要POSIX表达式$()

Please, don't use backticks as others said.

不要像其他人所说的那样使用反引号

The backquote (`) is used in the old-style command substitution, e.g.

反引号 ( `) 用于旧式命令替换,例如

foo=`command`

The

foo=$(command)

syntax is recommended instead. Backslash handling inside $() is less surprising, and $() is easier to nest. See

推荐使用语法。$() 中的反斜杠处理不那么令人惊讶,而且 $() 更容易嵌套。看

Despite of what Linus G Thiel said, $()works in sh, ash, zsh, dash, bash...

尽管 Linus G Thiel 说了些什么,但$()sh, ash, zsh, dash, bash...

回答by Pedro del Sol

you need backticks rather than single quotes

你需要反引号而不是单引号

` vs '

'对'