I have a script in home/me/bin with an alias in my .bashrc which reads a file xs.txt also in home/me/bin. I want the script to count the lines of the contents of xs.txt; however, if I run my alias from another folder --- say, Desktop --- xs.txt is not found:

num_comps=$(wc -l < xs.txt)

With the error message:

home/me/bin/upper: line 20: xs.txt: No such file or directory.
sed: can't read xs.txt: No such file or directory

How can I format this line so that no matter which cwd I am in, I can always read from xs.txt?


Found an answer with post https://stackoverflow.com/questions/32200811/bash-read-from-file-in-the-same-directory-as-the-script-file

What I forgot was that a new shell session was called from cwd, so I had to cd into where xs.txt was located. A simple:

TARGET = /home/me/bin

And the script works right as rain.

  • 4
    Note that assignments in shell scripts can not have spaces around the =. Your code, as currently written, would likely fail with a "command not found" error.
    – Kusalananda
    Dec 29 '20 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.