0

as the home directory?

I tried all 3 methods below but it just echos out the ~.

NAME="~/_root/repo/"

echo $NAME
echo "$NAME"
echo "${NAME}
Sun - FE
  • 369

2 Answers2

2

Have the shell expand the ~ before assigning it to NAME, by removing the quotes on the assignment statement.

NAME=~/_root/repo/
echo "$NAME"
AndyB
  • 180
1

There's no function for that. A tilde inside a string is just a tilde. You'll have to manually match and replace it with the value of $HOME:

var=${var}/
var=${var/#"~/"/"$HOME/"}
var=${var%/}

If you use 'eval', it interprets everything – it expands the tilde, but it also expands wildcards, it also expands variable substitutions, it also parses spaces, quotes, array syntax, and so on.

var="~/dir/file.txt"
eval "var=$var"

var="~/dir with spaces/file.txt"
eval "var=$var"

var="~/dir/file (1).txt"
eval "var=$var"
u1686_grawity
  • 452,512
  • Isn't there a way for the bash shell to act like a bash shell ... for example when I am in the bash shell and I type cd ~ it knows to change directory to my home directory. – Sun - FE May 19 '19 at 22:22
  • That's a different thing from what you originally asked. There's eval for interpreting a whole command line as if "typed in". There isn't anything for performing certain individual expansion steps. – u1686_grawity May 19 '19 at 22:24
  • The following answer is shorter than grawity's, but I'm making as a comment as I wish not to compete with grawity's answer, since the root of these answers are fundamentally the same. You can probably get desirable results by trying this: echo $( eval echo $( echo ${NAME} ) ) note the curly braces are different than the parenthesis – TOOGAM May 19 '19 at 23:27
  • 1
    @TOOGAM: That's a little redundant, you get the same with eval echo $NAME already. – u1686_grawity May 20 '19 at 04:23
  • @TOOGAM Nice combo. :) Please see this. – Kamil Maciorowski May 20 '19 at 05:15