Bash - Error parsing ~ in environment variable

773 views Asked by At

I have environment variable export MY_WORK_DIR="~/project". While I'm using below command, it give me an error:

realpath $MY_WORK_DIR

realpath: '~/project': No such file or directory

In my guess, the ~ is not processed while using this env variable.

BTW, export MY_WORK_DIR=~/project is not an option for me. ~ should be in the string.

Could you please guide me how to get real path from envrionment variable ~/project ?

EDIT

Sorry. The variable is from other app so I cannot modify the environment variable which contains tilde. (Storing variable with tilde expanded form is not an option).

EDIT2

Is it safe to use eval command like this? eval "echo ${MY_WORK_DIR}". It works for my use.

2

There are 2 answers

0
user1934428 On BEST ANSWER

I wouldn't use eval if I can avoid it. Especially in the way you are doing it, this is an invitation to do havoc by embedding dangerous code into MY_WORK_DIR.

A cheap solution for your concrete example would be to do a

if [[ ${MY_WORK_DIR:0:1} == '~' ]]
then 
  MY_WORK_DIR="$HOME/${MY_WORK_DIR:1}"
fi

which chops off the annoying ~ and prepends your home directory. But this would fail if MY_WORK_DIR is set to, say, ~einstein/project.

In this case, you would have to extract the user name (einstein) and search the home directory for this user.

3
Usama Abdulrehman On

Following steps can provide a resolution:

  1. You need to replace "~" with the full path of the project directory.
  2. Use pwd command to identify the full path of the project directory; e.g. /root/Documents/project is the full path you get.
  3. Execute this command export MY_WORK_PROJECT=/root/Documents/project
  4. Execute this command echo $MY_WORK_PROJECT so you should get this result /root/Documents/project