Unix: cree un directorio con el mismo nombre que el directorio de trabajo

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]?

preguntado el 04 de julio de 12 a las 05:07

2 Respuestas

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.

El 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)")"

Respondido 04 Jul 12, 21:07

$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

Respondido 04 Jul 12, 21:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.