8

What's wrong with the commands below?

$ var1="~/Music/$(date +%d%m%y)"
$ echo "$var1"
~/Music/240118
$ mkdir "$var1"
mkdir: cannot create directory ‘~/Music/240118’: No such file or directory

However

$ mkdir ~/Music/240118

works.

Never thought I would ask such questions after years of using bash...

| improve this question | | | | |
15

Tilde expansion doesn't work after the variable is expanded, so if you put a literal tilde in var, it will end up as a literal tilde to mkdir. (Note how the error message from mkdir has a literal tilde in it, not the actual path of your home directory.)

And, since you put the tilde in quotes in the assignment, it doesn't expand there either. If it's not in quotes, it does:

$ var="~/Music"; echo $var
~/Music
$ var=~/"Music"; echo $var
/home/me/Music

Of course, you could always just use $HOME instead:

$ var="$HOME/Music"; echo $var
/home/me/Music
| improve this answer | | | | |
  • Thanks. However I've noticed that this works either: $ var1=~/Music/"$(date +%d%m%y)" $ mkdir "$var1" – ka3ak Jan 25 '18 at 6:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.