在BASH中逐行循环文件内容

时间:2011-11-13 00:07:29

标签: bash shell terminal

我有一个名为installer.txt的文件,其中包含一行一行的.tar.gz文件,如:

http://oscargodson.com/projects/example1.tar.gz
http://oscargodson.com/projects/anotherexample.tar.gz
http://oscargodson.com/projects/onemore.tar.gz 

我试过了:

#!/bin/bash
file = `cat installs.txt`
for word in file; do
  echo $word
done

但我的输出如下:

Oscars-MacBook-Air:Desktop oscargodson$ ./test.sh
=:                                                     cannot open `=' (No such file or directory)
http://oscargodson.com/projects/example1.tar.gz:       cannot open `http://oscargodson.com/projects/example1.tar.gz' (No such file or directory)
http://oscargodson.com/projects/anotherexample.tar.gz: cannot open `http://oscargodson.com/projects/anotherexample.tar.gz' (No such file or directory)
http://oscargodson.com/projects/onemore.tar.gz:        cannot open `http://oscargodson.com/projects/onemore.tar.gz' (No such file or directory)
file

它应该输出每一行,或者,我想。想法?

1 个答案:

答案 0 :(得分:1)

您的错误实际上是由赋值语句生成的。你的作业周围不能有空格。总是引用rhs的好习惯。所以你想要的是

#!/bin/bash -u
file="$(cat installs.txt)"
for word in $file; do
  echo $word
done

我还将你改回$( ),因为这是推荐的方式,我觉得它也更容易阅读