Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

scripting

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

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

like image 963
primeminister Avatar asked Jan 25 '10 17:01

primeminister


People also ask

How do I run a command in a specific folder?

What to Know. Type cmd into the search bar to open the command prompt. Shift + right click in a window, then click Open PowerShell Window here to access the PowerShell interface. Open the folder you wish to access, then type cmd into the folder path at the top of the window to open a command prompt within the folder.

How do you cd into a directory within a directory?

The second way to list files in a directory, is to first move into the directory using the "cd" command (which stands for "change directory", then simply use the "ls" command. I'll type "cd Downloads/Examples" to change directories into the "Examples" directory that is inside the "Downloads" directory.

How do you run a file in another directory in Linux?

To use full path you type sh /home/user/scripts/someScript . sh /path/to/file is different from /path/to/file . sh runs /bin/sh which is symlinked to /bin/dash . Just making something clear on the examples you see on the net, normally you see sh ./somescript which can also be typed as `sh /path/to/script/scriptitself'.


2 Answers

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%            
like image 182
Noufal Ibrahim Avatar answered Sep 17 '22 16:09

Noufal Ibrahim


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

pushd /home/user/git/app && git tag -l; popd
like image 34
Hai Vu Avatar answered Sep 20 '22 16:09

Hai Vu