1 unstable release

0.0.1 Nov 6, 2023

#8 in #temporarily

Download history 40/week @ 2023-12-17 12/week @ 2024-02-18 83/week @ 2024-02-25 51/week @ 2024-03-03 69/week @ 2024-03-10 71/week @ 2024-03-17 61/week @ 2024-03-24 37/week @ 2024-03-31

243 downloads per month
Used in 3 crates


294 lines


A simple library for temporarily changing the current working directory.


Add this to your Cargo.toml:

pushd = "0.0.1"


use anyhow::Result
use std::path::PathBuf;
use pushd::Pushd;

fn main() -> Result<()> {
    // Current working directory is whatever it was before the call to
    // `write_in_etc`.

fn write_in_etc() -> Result<()> {
    let path = PathBuf::new("/etc");
    let _pd = Pushd::new(path)?;
    // Current working directory is now /etc
    // Do something in /etc.


This crate provides a Pushd type that temporarily changes the current directory.

When a Pushd struct is created it will call env::set_current_dir to change to the given directory. When the Pushd is dropped, it will change back to the original directory.

If the original directory doesn't exist, this error is ignored, since this may be because the original directory was a temporary directory. All other errors during drop cause a panic by default, but panics can be disabled entirely by using the Pushd::new_no_panic constructor.


use pushd::Pushd;
use std::path::PathBuf;

fn in_directory(path: PathBuf) {
    // When the current function exits and this variable is dropped, the
    // current directory will revert back to whatever it was before this
    // `Pushd` was created.
    let _pd = Pushd::new(path);
    // ...


The Pushd may panic if it cannot change back to the original directory when it's dropped. Use the new_no_panic constructor to prevent this.


~21K SLoC