Search code examples
shellunixmkdir

Unix: create a directory with the same name as the working directory


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


Solution

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