2

I need to read a file given to me in a script i made, the file can be any name, the input is as follows

./Naloga1.sh tocke < somefile.txt

This is the code i have:

while read line
do
  echo $line
done < 

The problem is, firstly if i put the script name at the done, it will read all the lines in my file - the last one. And secondly how can i acess the files name to then output it? If i echo $1 $2 $3, $1 comes as tocke and $2 and $3 dont exist

1 Answers1

2

< isn't an argument to the script, bash interprets that before your script is invoked. It redirects stdin for the script to come from, in this case, somefile.txt.

So you don't have to redirect anything to read from the file inside your script, it can just read from stdin because the shell has already handled the input redirection for you.

If you want to take the name of the file as an argument, just remove the < from your invocation and then the string somefile.txt will be stored in $2, which you can use to redirect input for your while loop if you like or any other purpose you might have.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • Thanks, do you maybe know how i would go about ignoring lines that start with "#" – LukaTheLegend Nov 29 '15 at 15:42
  • Within the loop you could do something like `if [[ "$line" =~ ^# ]]; then continue; fi` to see if it starts with `#` and continue the loop if it does – Eric Renouf Nov 29 '15 at 15:46
  • Regular expressions could solve that problem or just add in an if validating the first character that you've read in. Echo into a tmp variable, check the first char, if not # insert it. – L.P. Nov 29 '15 at 15:46