在BASH中逐行循环文件内容
我有一个名为installer.txt的文件,其中包含一行又一行的.tar.gz文件的URL,如:在BASH中逐行循环文件内容,bash,shell,terminal,Bash,Shell,Terminal,我有一个名为installer.txt的文件,其中包含一行又一行的.tar.gz文件的URL,如: 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 wo
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
它应该输出每一行,或者,我想。想法?您的错误实际上是由分配语句产生的。作业周围不能有空格。总是引用rhs是一种很好的做法。所以你想要的是
#!/bin/bash -u
file="$(cat installs.txt)"
for word in $file; do
echo $word
done
我还将您的qoutes改回了
$()
,因为这是推荐的方法,而且我认为它也更容易阅读您的错误实际上是由赋值语句生成的。作业周围不能有空格。总是引用rhs是一种很好的做法。所以你想要的是
#!/bin/bash -u
file="$(cat installs.txt)"
for word in $file; do
echo $word
done
我还将您的qoutes改为
$()
,因为这是推荐的方式,而且我认为它也更容易阅读谢谢。主要来自JavaScript背景和一些rails,这种语法对我来说很奇怪:)他在使用文件时也丢失了$
——我看到你也修复了这个问题。另外,shebang中的-u是什么意思?谷歌搜索了它,但没有用。-u
表示如果引用未设置的变量,脚本将打印错误。非常有用的捕捉打字错误。e、 g.如果你不小心有了echo$wrod
它只会打印空行。但是使用-u
它会打印一条错误消息,说wrod
是一个未定义的变量谢谢。主要来自JavaScript背景和一些rails,这种语法对我来说很奇怪:)他在使用文件时也丢失了$
——我看到你也修复了这个问题。另外,shebang中的-u是什么意思?谷歌搜索了它,但没有用。-u
表示如果引用未设置的变量,脚本将打印错误。非常有用的捕捉打字错误。e、 g.如果你不小心有了echo$wrod
它只会打印空行。但使用-u
时,它会打印一条错误消息,说明wrod
是一个未定义的变量