How can I execute a command inside another folder and return to original directory?

Viewed 372

I use this command to make inside a folder:

cd build/ && make 

But I want to return to original directory after the command

I tried this:

cd build/ && make && cd ..

But this doesn't work. How can I do it? Would help in quick testing...

5 Answers

Use a subshell, like so:

$ pwd
/tmp

$ (cd build && make)

$ pwd
/tmp

The shell forks before running the commands in brackets, so once it completes it's as if you never left the current directory.

Sounds like you want pushd and popd.

The pushd command will push the current directory onto a stack, saving it and allowing you to change to some other directory. The popd command will pop the last saved directory from the stack.

You can use below commands

cd build; 
make;
cd -

Use popd/pushd:

pushd build ; make ; popd

I would propose the following command:

cd $DIR && make && cd -; 

to return to the previous directory after running your make, this work even if the path in $DIR is long.

If you want to go for more sophisticate tools like playing with a stack of accessed directory you can use:

pushd, popd 

Usage:

$ pushd some_directory
It acts as a:
$ cd some_directory
except that some_directory is also added to the stack.
"$ pushd ~/TMP  # we're in ~/
~/TMP ~
$ pushd ~/DATA  # now we're in ~/TMP
~/DATA ~/TMP ~
$ pushd ~  # now we're in ~/DATA
~ ~/DATA ~/TMP ~
$ popd   # now we're in ~/
~/DATA ~/TMP ~
$ popd   # now we're in ~/DATA
~/TMP ~
$ popd   # now we're in ~/TMP
~
$    # now we're in ~/"

another very good approach is this function that I really likes:

"cd_func ()
{   
    local x2 the_new_dir adir index;
    local -i cnt;
    if [[ $1 == ""--"" ]]; then
        dirs -v;
        return 0;
    fi;
    the_new_dir=$1;
    [[ -z $1 ]] && the_new_dir=$HOME;
    if [[ ${the_new_dir:0:1} == '-' ]]; then
        index=${the_new_dir:1};
        [[ -z $index ]] && index=1;
        adir=$(dirs +$index);
        [[ -z $adir ]] && return 1;
        the_new_dir=$adir;
    fi;
    [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir=""${HOME}${the_new_dir:1}"";
    pushd ""${the_new_dir}"" > /dev/null;
    [[ $? -ne 0 ]] && return 1;
    the_new_dir=$(pwd);
    popd -n +11 2> /dev/null > /dev/null;
    for ((cnt=1; cnt <= 10; cnt++))
    do  
        x2=$(dirs +${cnt} 2>/dev/null);
        [[ $? -ne 0 ]] && return 0;
        [[ ${x2:0:1} == '~' ]] && x2=""${HOME}${x2:1}"";
        if [[ ""${x2}"" == ""${the_new_dir}"" ]]; then
            popd -n +$cnt 2> /dev/null > /dev/null;
            cnt=cnt-1;
        fi;
    done;
    return 0
}"

In your profile/bashrc, alias cd to this function:

alias cd=cd_func

and then you can type:

"$ cd --
 0  ~
 1  ~/DATA
 2  ~/TMP"

to see all the directories you've visited. To go ~/TMP, for example, enter:

$ cd -2
Related