Strange way to use mkdir

I was looking at this with mkdir. Will this create two directories dirname /nosuchdirectory/hi.txt? Why are they in backticks?

 mkdir -p `dirname /nosuchdirectory/hi.txt` && cp -r urls-resume /nosuchdirectory/hi.txt

hi, have you tried to execute this ?
if not, why not try and see the behaviour ?
come back with questions/answers once you've done that
I presume you know what xxxxx does ?

look forwards to hearing back.

1 Like

Permission denied. Is this because I am using a really old OS? Not sure what else would cause that.

well the example you've supplied is attempting to create a top level directory /nosuchdirectory
so, unless you have root permission ... you'll get permission denied.
try sticking a . in front of it './nosuchdirectory' (in all mentions of that) and see what happens

For me the first part of the line is clear enough what to expect but the second part was a bit misleading/strange and needed execution to see the exact result. The OS didn't think like me/human that hi.txt should be a file.

It was good that you asked. The backticks are important and non-obvious. And it's wise to understand what a command will do before you execute it. Backticks are shell syntax that executes the shell command contained within the backticks (i.e. dirname /nosuchdirectory/hi.txt) and replaces the backticked-command with its output on the surrounding shell command. This is an amazingly powerful feature of shell scripting.

There is a modern (bash?) alternative syntax to backticks that you might be more familiar with. $(cmd arg...). It is the same as BACKTICK cmd arg... BACKTICK (surrounded by backticks but I don't know how to include backticks when backticks are used on this site for style purposes).

Back to your question: The mkdir command makes use of the the dirname command to construct its arguments. If you read the manual entry for dirname, you will see that it strips the last component from the file path.

So the output of dirname /nosuchdirectory/hi.txt would be /nosuchdirectory.

So the actual command executed would be mkdir -p /nosuchdirectory && cp -r urls-resume /nosuchdirectory/hi.txt

I can only assume that whoever wrote the command that you are considering assumed that you would replace /nosuchdirectory with some directory that actually made sense in your environment.

Otherwise, you will need to execute the command as root to have the permission to create a new directory under the root directory (/). But it's very unlikely that you want to do that.

Like all code you can enclose backticks in triple-backticks. Try the symbols at the top of the Wiki editor.

 ``` inline code with `backticks` ```
```
code block
with `backticks`
```
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.