Bash – How to compare the two file paths in shell script

bash

I am trying to compare my working directory with a correct directory from which the script needs to run. Here is snippet of shell script

CURR_DIR=echo pwd
echo $CURR_DIR
if [ "$CURR_DIR" == "/proj/project_a/scripts_shell" ]; then
    echo "You are running script from correct directory"
fi

In this case I ensured that I am in /proj/project_a/scripts_shell (as my present working directory) but for some reason it is not able to detect this in the if statement. Thus it is not printing the message.

What is wrong with this?

Best Answer

Try this:

if [ "$PWD" = "/proj/project_a/scripts_shell" ]; then
    echo "You are running the script from the correct directory" 
fi

The problem is that when you do CURR_DIR=echo pwd, the shell calls pwd with the environment variable CURR_DIR set to echo. When you need to capture the output of a command in a variable, just do VAR=$(cmd).

Related Question