0

There are -p option in mkdir command to create parent directories as needed

wolf@linux:~$ tree
.

0 directories, 0 files
wolf@linux:~$ 
wolf@linux:~$ mkdir dir1/dir2/dir3
mkdir: cannot create directory ‘dir1/dir2/dir3’: No such file or directory
wolf@linux:~$ 
wolf@linux:~$ tree
.

0 directories, 0 files
wolf@linux:~$ 
wolf@linux:~$ mkdir -p dir1/dir2/dir3
wolf@linux:~$ 
wolf@linux:~$ tree 
.
└── dir1
    └── dir2
        └── dir3

3 directories, 0 files
wolf@linux:~$ 

Are there similar features in vi or touch command?

In this case, I would like to create file authorized_keys in nonexistent directory .ssh with vi or touch.

authorized_keys is a file, and not a directory. Hence, mkdir -p .ssh/authorized_keys command is not applicable here as authorized_keys will be created as directory, not a file.

wolf@linux:~$ ls .ssh
ls: cannot access '.ssh': No such file or directory
wolf@linux:~$ 

Would it be possible to do this without mkdir .ssh or mkdir -p .ssh?

wolf@linux:~$ touch .ssh/authorized_keys
touch: cannot touch '.ssh/authorized_keys': No such file or directory
wolf@linux:~$ 
6
2

To create the ~/.ssh directory, best is to let ssh create it itself, then you know it will be created with the right permissions.

ssh localhost

(or :!ssh localhost from within vi)

And accept the key for localhost, will cause ssh to create the .ssh directory and a known_hosts file within.

To make the directory within vi, you can also do:

:!mkdir -m a=,u=rwx .ssh

In vim, you can do

:!mkdir -pm a=,u=rwx %:h

or using its own mkdir():

:call mkdir(expand("%:h"),"p",0700)

Where % is the currently edited file and :h like in csh/zsh returns the dirname (head). You could map that to a key or key combination or custom function if you find yourself needing it often though you'd need to find a way to specify the permissions (here a=,u=rwx / 0700 so only the owner has read+write+search permission to it).

About mkdir+touch, see: Zsh: How to create a directory and file inside it with one command?

2
  • Thanks for the tips. So I guess -p option in mkdir command or something similar is not available in vi or touch right? – Wolf Aug 13 '20 at 8:26
  • 1
    @Wolf, vi can run arbitrary commands with its ! ex command. vim also has its own mkdir() function. – Stéphane Chazelas Aug 13 '20 at 9:00
1

AFAIK, you can't force create a directory with vi or touch.

You still need to create it with mkdir, or use it with -p flag.

-p, --parents     no error if existing, make parent directories as needed

If there is a way to do that with vi or touch, feel free to update the answer.

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