how to use bash variable with realpath command in a script?

507 views Asked by At

realpath ~/test outputs /home/<user>/test.
Now, I have to use this in my bash script, so I have the path stored in a variable.
If I run the below commands in my shell it works.

export REMOTE_DIR=~/test
realpath $REMOTE_DIR

I have following script:

while true; do
    read -p "Enter the path of the Repository : " REMOTE_DIR
    if [ -d $(realpath $REMOTE_DIR) ]; then
            break;
    else
            echo "Path not found!! Please enter a valid path."
    fi
done

But I get the following error, realpath: '~/test': No such file or directory.

I observed that the same error occurs when I enclose path in quotes(double or single) as following:

export REMOTE_DIR='~/test'
realpath $REMOTE_DIR

I think the error has to do with something going wrong in the if statement condition. I guess the $REMOTE_DIR outputs '~/test' instead of ~/test.

What am I doing wrong?

EDIT :
Another issue in the same code: On inputting, ~/test, Path not found is output for the following code.

while true; do
    read -p "Enter the path of the Repository : " REMOTE_DIR
    if [ -d "$REMOTE_DIR" ]; then
            break;
    else
            echo "Path not found!! Please enter a valid path."
    fi
done

PS : I'm new to bash scripting!

1

There are 1 answers

1
erik258 On

As part of a bash command, ~/ expands to the user's home directory. But read does not do this:

% read p                                                                
~/test
% echo $p                                                               
~/test

One solution would be to use a parameter to pass the REMOTE_DIR and let the shell invoking the script handle expansion:

#!/bin/bash
REMOTE_DIR="$1"
if [ ! -d "$REMOTE_DIR" ]; then
  echo "Not a directory: $REMOTE_DIR";
  exit 1;
fi
% ./t.sh ~/does-not-exist                                                 
Not a directory: /Users/user/does-not-exist

Using read to interactively prompt for user input is not common in the real world. Most programs will expect to be invoked with command line parameters.