Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何在另一个文件夹中执行命令并返回到原始目录?_Linux_Bash_Unix - Fatal编程技术网

Linux 如何在另一个文件夹中执行命令并返回到原始目录?

Linux 如何在另一个文件夹中执行命令并返回到原始目录?,linux,bash,unix,Linux,Bash,Unix,我使用此命令在文件夹中创建: cd build/ && make 但我想在命令执行后返回原始目录 我试过这个: cd build/ && make && cd .. 但这不起作用。我怎么做?将有助于快速测试…听起来像你想要的 pushd命令将当前目录推送到堆栈上,保存它并允许您更改到其他目录。popd命令将从堆栈中弹出最后保存的目录 使用popd/pushd: pushd build ; make ; popd 我提议如下命令: cd $D

我使用此命令在文件夹中创建:

cd build/ && make 
但我想在命令执行后返回原始目录

我试过这个:

cd build/ && make && cd ..
但这不起作用。我怎么做?将有助于快速测试…

听起来像你想要的

pushd
命令将当前目录推送到堆栈上,保存它并允许您更改到其他目录。
popd
命令将从堆栈中弹出最后保存的目录

使用popd/pushd:

pushd build ; make ; popd

我提议如下命令:

cd $DIR && make && cd -; 
要在运行make后返回上一个目录,即使$DIR中的路径很长,也可以执行此操作

如果您想使用更复杂的工具,如使用一堆访问过的目录,您可以使用:

pushd, popd 
用法:

$ 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 ~/"
另一个非常好的方法是我非常喜欢的函数:

"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
}"
然后您可以键入:

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

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

$ cd -2

使用子shell,如下所示:

$ pwd
/tmp

$ (cd xyz && make)

$ pwd
/tmp

shell在运行括号中的命令之前分叉,因此一旦完成,就好像您从未离开过当前目录。

您可以使用以下命令

cd build; 
make;
cd -

谢谢这就是我一直在寻找的。对于脚本来说可能比cli更好。这也是为什么在脚本中运行命令不会更改工作目录的原因。
cd build; 
make;
cd -