0

I have a very simple script reading a text file which is in a different directory:

IFS=$'\n' read -d '' -r -a urls < ../dat/urls.txt

This works fine when running the script from the directory the script is in e.g) ./fetch_urls

But if I run the script from the say the user home or via cron it fails to resolve the urls.txt file. e.g.

/home/my-user/data-transfer/fetch_urls.sh

It fails with:

line 3: ../dat/urls.txt: No such file or directory

Is there some way to make it work so it always resolves correctly the urls.txt file. Or maybe I have to pass the location of urls.txt as a parameter?

Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
user1472672
  • 313
  • 1
  • 9

2 Answers2

1

Your file is relative to the directory of your script. You can get it with:

script_dir=$(dirname "$0")

You now have two solutions:

  • Either cd to that directory before accessing urls.txt. I personally don't do this as it may break other relative paths (e.g. paths given on the command line)

  • Or, better, prefix your relative paths with that directory:

    IFS=$'\n' read -d '' -r -a urls < "$script_dir/../dat/urls.txt"
    
xhienne
  • 5,738
  • 1
  • 15
  • 34
0

First you need to resolve the current directory of the launched script (fetch_urls.sh in your example).

myPath=$( which $0 )
currentDir=$( dirname "$myPath" )

Then, you simply have to fix your line in your script:

IFS=$'\n' read -d '' -r -a urls < "$currentDir/../dat/urls.txt"
Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44