Search code examples
bashdouble-quotestilde-expansion

Bash - Error parsing ~ in environment variable


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.


Solution

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