---
title: "cdtmp: change to a temporary directory"
url: https://perrotta.dev/2024/10/cdtmp-change-to-a-temporary-directory/
last_updated: 2026-02-16
---


Sometimes I need to do random experimentation in a throwaway directory.

For that, I have the following `cdtmp` function in my shell:

```shell
cdtmp () {
	builtin cd "$(mktemp -d "/tmp/$USER-${1:+$1-}$(date +%Y-%m-%d)-XXXXXX")" || return
	builtin pwd
}
```

Here are two example usages:

```shell
% cdtmp
/tmp/thiago-2024-10-07-V3c3Na
thiago@thiagoperrotta-MacBook-Pro /tmp/thiago-2024-10-07-V3c3Na
% cdtmp devops
/tmp/thiago-devops-2024-10-07-P4W1fh
```

This idea was built upon [Alex Kotliarskyi's](https://frantic.im/cdtmp/), which
he describes as:

> It's a super simple alias that creates a temporary directory and then jumps
> into it. Here are a few examples of what I use it for:
>
> — Clone a random interesting git repo to experiment with

I also use it for testing one-off bash, C++, golang or python scripts, for
example:

```shell
% cdtmp
/tmp/thiago-2024-10-07-F5aFrJ
thiago@thiagoperrotta-MacBook-Pro /tmp/thiago-2024-10-07-F5aFrJ
% vim main.sh
thiago@thiagoperrotta-MacBook-Pro /tmp/thiago-2024-10-07-F5aFrJ
% bash main.sh
hello world
```

[The function definition in my dotfiles](https://github.com/thiagowfx/.dotfiles/blob/3645ea5811d07c9f4be3cea91c0ffaf43ba4071c/profile/.profile.d/functions.sh#L5).

