mkdir: cannot create directory: No such file or directory

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…

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x