Home > OS >  Check if file exist relative to current script (one level up)
Check if file exist relative to current script (one level up)

Time:10-03

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

CodePudding user response:

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
  • Related