Oscar Godson
Oscar Godson

Reputation: 32726

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?

Upvotes: 1

Views: 497

Answers (1)

Sodved
Sodved

Reputation: 8588

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

Upvotes: 1

Related Questions