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.
- To store the output of a command in a variable, use
$(), not${}. [ -f "$dir" ]checks if$diris a a file, which will never happen, becausedirnameoutputs a directory.- 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
