Reputation: 8319
Let's say I was in /var/www/foo
and I wanted to create /tmp/foo
. Is there a way I can do that programmatically and end up with a command like mkdir /tmp/[insert something here]
?
Upvotes: 0
Views: 264
Reputation: 107769
$PWD
always contains the full path to the current directory. Hence ${PWD##*/}
($PWD
except the part up to the last /
) is the name of the current directory.
mkdir "/tmp/${PWD##*/}"
You can leave out the double quotes if you know that the name of the current directory doesn't contain any whitespace or any of the characters *?\[
.
In zsh, there is a simpler way of extracting the last component of a path:
mkdir -- /tmp/$PWD:t
Upvotes: 0
Reputation: 46806
mkdir /tmp/`basename $(pwd)`
(Note that they are backticks, not forward ticks.)
This works because the backticks do command substitution. It basically runs the stuff in the backticks and replaces it with standard out of the command run. In this case the basename
command with the current working path. And $(…)
does exactly the same as the backticks.
The basename
command "strip directory and suffix from filenames". (see http://unixhelp.ed.ac.uk/CGI/man-cgi?basename)
You could also use (if you didn't want to have the backticks):
mkdir /tmp/$(basename $(pwd))
Note that if the path to the current directory contains spaces or other special characters, you need to put the command substitutions in double quotes:
mkdir "/tmp/$(basename "$(pwd)")"
Upvotes: 3