Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading files line by line in by using for loop bash script [duplicate]

Tags:

bash

for-loop

Say for example I have a file called "tests",it contains

a
b
c
d

I'm trying to read this file line by line and it should output

a
b
c
d

I create a bash script called "read" and try to read this file by using for loop

#!/bin/bash
for i in ${1}; do //for the ith line of the first argument, do...
   echo $i  // prints ith line
done

I execute it

./read tests

but it gives me

tests

Does anyone know what happened? Why does it print "tests" instead of the content of the "tests"? Thanks in advance.

like image 493
OKC Avatar asked Oct 29 '25 07:10

OKC


2 Answers

#!/bin/bash
while IFS= read -r line; do
  echo "$line"
done < "$1"

This solution can handle files with special characters in the file name (like spaces or carriage returns) unlike other responses.

like image 152
Gilles Quenot Avatar answered Oct 31 '25 07:10

Gilles Quenot


You need something like this rather:

#!/bin/bash
while read line || [[ $line ]]; do
  echo $line
done < ${1}

what you've written after expansion will become:

#!/bin/bash
for i in tests; do
   echo $i
done

if you still want for loop, do something like:

#!/bin/bash
for i in $(cat ${1}); do
   echo $i
done
like image 33
bobah Avatar answered Oct 31 '25 06:10

bobah