0

There are these two files in the directory:

$ ls -l
script.sh
sources.txt

The script.sh does the following:

#!/bin/bash
sed -i 's/\r//g' ./sources.txt

while read -r source
do
    echo "$source"
done < ./sources.txt

Everything works fine when the script gets executed from the directory containing it, so:

$ sh ./script.sh

But when I tried to test absolute path before putting it into crontab, I got the following error:

$ sh /var/tmp/scripts/script.sh
sed: ./sources.txt: No such file or directory
/var/tmp/scripts/script.sh: line 4: can't open ./sources.txt: no such file

The script will always be coupled with the sources.txt file. How to ensure the script can import the source file without specifying absolute path?

AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52
  • See https://stackoverflow.com/questions/59895/how-do-i-get-the-directory-where-a-bash-script-is-located-from-within-the-script – konsolebox Jan 25 '23 at 17:52
  • This is [BashFAQ #28](https://mywiki.wooledge.org/BashFAQ/028). – Charles Duffy Jan 25 '23 at 17:57
  • 1
    BTW, when you run `sh yourscript`, you aren't running it as a _bash_ script, you're running it as a _sh_ script; starting your script with `sh` makes bash extensions unavailable (exactly which extensions become unavailable depends on your operating system, but even on OSes where `sh` is a symlink to `bash` it turns off _some_ features for better POSIX compliance when started under the `sh` name). – Charles Duffy Jan 25 '23 at 17:57
  • 1
    ...that's particularly important if you're going to use one of the more reliable solutions for your problem that makes use of `$BASH_SOURCE` instead of relying on `$0`; as the name of `BASH_SOURCE` implies, it's a _bash_ feature, not a _sh_ feature. – Charles Duffy Jan 25 '23 at 18:03

0 Answers0