How to Move Directory into a Directory with the Same Name

directorymacosmv

I have a directory foo with several files:

.
└── foo
    ├── a.txt
    └── b.txt

and I want to move it into a directory with the same name:

.
└── foo
    └── foo
        ├── a.txt
        └── b.txt

I'm currently creating a temporary directory bar, move foo into bar and rename bar to foo afterwards:

mkdir bar
mv foo bar
mv bar foo

But this feels a little cumbersome and I have to pick a name for bar that's not already taken.

Is there a more elegant or straight-forward way to achieve this? I'm on macOS if that matters.

Best Answer

To safely create a temporary directory in the current directory, with a name that is not already taken, you can use mktemp -d like so:

tmpdir=$(mktemp -d "$PWD"/tmp.XXXXXXXX)   # using ./tmp.XXXXXXXX would work too

The mktemp -d command will create a directory at the given path, with the X-es at the end of the pathname replaced by random alphanumeric characters. It will return the pathname of the directory that was created, and we store this value in tmpdir.1

This tmpdir variable could then be used when following the same procedure that you are already doing, with bar replaced by "$tmpdir":

mv foo "$tmpdir"
mv "$tmpdir" foo
unset tmpdir

The unset tmpdir at the end just removes the variable.


1 Usually, one should be able to set the TMPDIR environment variable to a directory path where one wants to create temporary files or directories with mktemp, but the utility on macOS seems to work subtly differently with regards to this than the same utility on other BSD systems, and will create the directory in a totally different location. The above would however work on macOS. Using the slightly more convenient tmpdir=$(TMPDIR=$PWD mktemp -d) or even tmpdir=$(TMPDIR=. mktemp -d) would only be an issue on macOS if the default temporary directory was on another partition and the foo directory contained a lot of data (i.e. it would be slow).

Related Question