开发者

How do I execute a command from a specific directory without actually changing to that directory

I want to execute a command like 'git tag -l' inside a directory /home/user/git/app/ but I am actually in /home/user. How can I do that in bash without changing my working directory?

So NOT:

cd /home/user/git/app && git tag -l
开发者_Go百科

because that actually changes my working directory and have to do 'cd /home/user' again.


Just bracket the whole thing. That will run it in a subshell which can go to any directory and not affect your 'current working' one. Here's an example.

noufal@sanctuary% pwd
/tmp/foo
noufal@sanctuary% (cd ../bar && pwd && ls -a )
/tmp/bar
./  ../
noufal@sanctuary% pwd
/tmp/foo
noufal@sanctuary%            


Here is another solution: use pushd to change directory, then popd to return:

pushd /home/user/git/app && git tag -l; popd


If the command in question is always going to be a git command, you should just use the --git-dir and --work-tree options to tell git what to do! (Or if you're doing this a lot over the course of a script, set the variables GIT_DIR and GIT_WORK_TREE to the appropriate paths)

If this is a general question, I believe Andrzej has a start on the best suggestion: use a subshell. The proper way to start a subshell, though, is to use parentheses, not to use command substitution (unless you actually want to capture the output):

( cd $dir && run_command )

The other solution, as suggested by Felix and ibread, will of course work, but do be careful - if the command you're executing is perhaps a shell function, then it could also cd, and change the effect of the cd - at the end. The safest thing in the general case is to store the current directory in a variable first.


You might want to do something like (cd /home/user/git/app && git tag -l). This spawns a new shell and executes the commands in the shell without changing your shell. You can verify this by executing the following:

$ echo $OLDPWD
/Users/daveshawley
$ (cd / && ls)
...
$ echo $OLDPWD
/Users/daveshawley


try to use

cd -

after everything is done. This command is used to go back to your last working directory.


The following function can be added in the .bashrc

execute_under_directory()
{
    if [ $# -lt 2 ] 
    then
        echo "usage: execute_under_directory <DIRECTORY_PATH> <COMMAND>"
        return 1
    fi

    local current_directory=$(pwd)
    cd $1

    shift
    "$@"

    cd $current_directory
}

And by also adding an alias, for example

alias eud=execute_under_directory

, you can run any command just like this:

eud path/to/project git tag -l


Use cd - after your command

cd my/dir1/.test1 && cd - && cd my/dir2/.text2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜