简体   繁体   中英

Looping file contents line by line in BASH

I have a file called installer.txt which will contain a line by line of URLs of .tar.gz files like:

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

And I tried:

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

But my output is like:

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

It should output each line, or, so i thought. Ideas?

You errors are actually being generated by the assignment statement. You cant have spaces around your assignment. And its good practice to always quote the rhs. So what you want is

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

I also changed you back qoutes to $( ) as this is the recommended way and I think its easier to read too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM