Filepaths are relative to current working directory

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-04-25

Deeply nested in ./lib/tasks/maintenance.rake I had some code that referenced a JSON validator which lived in ./bin/validate_json). Here was the rake code:

# inside ./lib/makes/maintenance.rake
raise 'Invalid data' unless system('../../bin/validate_json')

I ran the program from ., the folder containing both lib and bin.

This failed at running the validate_json file referenced by the path ../../bin/validate_json. Ultimately this is because paths should be relative to the file that starts the program.

What I should have had instead was a reference to the file from . (instead of relative to the nested rake file). Ideally this is what I needed;

# inside ./lib/makes/maintenance.rake
raise 'Invalid data' unless system('./bin/validate_json')

Alternatively, there are special tools for referencing some file relative to the file in question directory. In Ruby, the following would have worked too:

raise 'Invalid data' unless system(File.join(File.dirname(__FILE__), '../../'))

Lesson

By default, paths references within your code must be relative to where your program started (the root working directory where your entry point is), not to the current file.