Linux Bash - 因为我是猫?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10068890/
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-08-06 05:41:07  来源:igfitidea点击:

Bash - for i in cat?

linuxbash

提问by Alasdair

I'm not a bash scriptor, so this is no doubt a very simple question.

我不是 bash 脚本编写者,所以这无疑是一个非常简单的问题。

I have a bash script throwing an error. It looks like this:

我有一个 bash 脚本抛出错误。它看起来像这样:

#!/bin/bash
for i in (cat /root/list.txt)
do
        doSomething
done

The error is on the second line, related to the curly brackets. So it seems curly brackets shouldn't be here... in which case, what should line 2 look like?

错误在第二行,与大括号有关。所以看起来大括号不应该在这里......在这种情况下,第2行应该是什么样子?

The script is supposed to read each line out of /root/list.txt and then doSomething with this (I removed the actual command for this example.)

该脚本应该从 /root/list.txt 中读取每一行,然后用它做一些事情(我删除了这个例子的实际命令。)

Thanks!

谢谢!

采纳答案by geekosaur

Probably

大概

for i in $(cat /root/list.txt)

回答by Ignacio Vazquez-Abrams

You should not use a for loop to read lines. Use a while read loop instead.

您不应该使用 for 循环来读取行。改用 while 读取循环。

#!/bin/bash
while read -r i; do
  doSomething
done < /root/list.txt

回答by mah454

You can debug your bash script with :

您可以使用以下命令调试 bash 脚本:

set -x

Use this :

用这个 :

for line in $(cat /etc/fstab)
do 
   echo $line ; sleep 1
done

Or this :

或这个 :

while read line
do
    echo $line ; sleep 1
done < /etc/fstab

Note : line is variable

注意:线是可变的

回答by weima

try

尝试

#!/bin/bash
for i in `cat /root/list.txt`
do
    doSomething
done