0

I'm trying to use a variable with mkdir but it does not create a new directory. If I try without the variable it works fine.

[kurs@localhost ~]$ K="~/a/`date +%Y%m%d`"
[kurs@localhost ~]$ echo $K
~/a/20190926
[kurs@localhost ~]$ mkdir $K
mkdir: nie można utworzyć katalogu „~/a/20190926”: Nie ma takiego pliku ani katalogu
[kurs@localhost ~]$ 
[kurs@localhost ~]$ mkdir ~/a/20190926
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
sqra
  • 11
  • 1
  • 3

2 Answers2

2

The problem isn't the mkdir command, but the variable assignment. ~ is only expanded to your home directory if you leave it unquoted. If you quote it you get a literal tilde character. Leave out the double quotes.

$ K=~/a/`date +%Y%m%d`
$ echo $K
/home/kurs/a/20190926
$ mkdir $K

It's a good idea to quote variable expansions or else file names with spaces and other unusual characters will mess you up. I recommend you write:

$ mkdir "$K"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

I suspect that "a" directory doesn't exist. Use the command with -p option mkdir -p $K. It will create all missing intermediate directories. Update: as per Mihir suggestion - "~" will be treated as the name for a new directory, it won't use HOME directory as parent for "a", to avoid it set your K variable using $HOME instead of "~".

jaroslawj
  • 462
  • 2
  • 12