0

I'm trying to figure out why

[ -d ~/dir ] ; echo $?

indeed returns 0, if dir exists and is a directory, but

DIR="~/dir" ; [ -d "${DIR}" ] ; echo $?

always returns 1.

echo "${DIR}"

prints ~/dir, as expected. I am given a text file containing path to another file, and thought I'd use cat to store the content inside a variable. What is the proper way to do this?

  • http://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash/27485157#27485157 – ewcz Mar 08 '17 at 10:40

3 Answers3

0

The tilde expansion happens before the variable expansion, see EXPANSION in man bash. ~ is not a real path, it's expanded by the shell to the real path, but it doesn't happen for paths stored in a variable. Store the real full path in the variable instead.

choroba
  • 231,213
  • 25
  • 204
  • 289
0

not really a bash solution but you could do:

DIR="~/dir" ;

#expand the tilde
DIR=$(python -c "import os;print(os.path.expanduser('${DIR}'));");

[ -d "${DIR}" ] ; echo $?
ewcz
  • 12,819
  • 1
  • 25
  • 47
0

DIR = "$HOME/dir" would work fine.

Areeb
  • 366
  • 1
  • 3
  • 16