-1

I have this folder structure.

myFolder
 - script.sh
 - test.txt

In my script.sh, I wrote this code:

filepath = "test.txt"
while read line || [ -n "$line" ]
do
    this this this
done < filepath

I open terminal in myFolder, I type bash script.sh and I have this error:

No such file or directory

But test.txt contains 1 line.

Why do I have this error?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Cohchi
  • 543
  • 3
  • 9
  • 19
  • 1
    Do you have a command called `filepath`? You've written `filepath = "test.txt"` but that runs the command `filepath` with two arguments: `=` and `test.txt` (since the shell removes the double quotes). Also, your redirection looks for a file `filepath` (again); you probably intended to write `$filepath` which would look at the value in the variable — if the variable had been set. Run your code past [Shell Check](https://www.shellcheck.net/) and see what it says. – Jonathan Leffler Mar 28 '20 at 16:01
  • And, in general, it would be best to use double quotes around `"$filepath"` in the redirection, though with the fixed name shown, it isn't critical (there are no spaces to preserve, etc). – Jonathan Leffler Mar 28 '20 at 16:17

1 Answers1

0

Bash is actually quite sensitive about spaces. Also, you need to make sure you reference filepath as $filepath.

# no spaces around the equals sign
filepath="test.txt"
while read line || [ -n "$line" ]
do
    this this this
done < $filepath
# note the added $ above
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • See [How to Answer](https://stackoverflow.com/help/how-to-answer) -- questions that have been asked and answered many times before should be closed as duplicates so their answers can be centralized rather than spread out throughout the knowledgebase. – Charles Duffy Mar 28 '20 at 16:08
  • (Not my downvote, though -- while it's best not to add such answers, it's also not accepted practice to downvote them when accurate / otherwise acceptable. That said, it looks a little less like trying to game the system for rep if known-duplicate answers are added with the "community wiki" flag set). – Charles Duffy Mar 28 '20 at 16:10
  • Finding the right duplicate is a complete PITA. I wonder if the [Upcoming Feature: New Question Close Experience](https://meta.stackoverflow.com/q/394871/15168) is going to improve the tools for identifying duplicates? – Jonathan Leffler Mar 28 '20 at 16:15