简体   繁体   中英

Reading lines from a file in a bash script

I am banging my head against some syntax wall I think, and I'm not sure what's going wrong. I had a bash script that used to run on an older version of Redhat, but for some reason it's not running on our Linux server. In any case, I tried to update and here's what I have now...

UPDATED per comment suggestion:

#!/bin/bash
while read -r line;
do
     echo "this is species no. $line";
done < "$1"

Ultimately, what I'll want this to do is pass those numbers to an R script, but no matter now. It doesn't seem to like the passing of a file at the end of the script (I get a "syntax error near unexpected token 'done'). However, when I take that out, it says "unexpected end of file." What's going wrong?

In case it matters, the server is running bash 4.2.25.

The syntax of your code is perfect, though I would probably put an IFS in there and drop the redundant semi-colon.

I suspect that the line endings in your file are causing the error. The script below should handle that... but the best way to know for sure would be to run your script with a new small test file of names.

while IFS= read -r line; do
    echo "$line"
done < <(sed 's/^M$//' "$1")

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