0

How to check/get file path relative to current script?

Script is running from ..../app/scripts/dev.sh

File to check from ..../app/dist/file.js

dir="${BASH_SOURCE%/*}../dist/backend.js"
if [ -f ${dir} ]; then
    echo "file exists. ${dir}"
else 
    echo "file does not exist. ${dir}"
fi

ZiiMakc
  • 31,187
  • 24
  • 65
  • 105

1 Answers1

1

There are three problems in your script.

  1. To store the output of a command in a variable, use $(), not ${}.
  2. [ -f "$dir" ] checks if $dir is a a file, which will never happen, because dirname outputs a directory.
  3. Your script can be executed from any other working directory as well. Just because the script is stored in ···/app/scripts/ does not mean it will always run from there.

Try

file=$(dirname "$BASH_SOURCE")/../dist/file.js
if [ -f "$file" ]; then
    echo "file exists."
else 
    echo "file does not exist."
fi
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • problem is that pwd is different, so i need to use `./dist/backend.js` to work(one dot), but I want to use relative path from script location to be able to run script from anywhere – ZiiMakc Oct 02 '21 at 15:10
  • Then your question is a duplicate of https://stackoverflow.com/q/6659689/6770384 – Socowi Oct 02 '21 at 15:11
  • I don't get how to go one level up :( – ZiiMakc Oct 02 '21 at 15:16
  • @ZiiMakc You can use `..` on any directory of a path to go one level up. For example `a/b/c/../../b/../b/` is the same as `a/b/`. See my edited answer. – Socowi Oct 02 '21 at 15:21