You have a few options. You can either group the commands with &&
or ;
. Like this:
cd subdir && git init && cd ..
or
cd subdir; git init; cd ..
The difference between these is that in the first example, if one of the commands fails, it will not execute the rest of them. In the second example, all of the commands will run no matter what.
Another option would be to define a function and use it, for instance:
function cdinit() {
cd $1
git init
cd ..
}
Then you can run the command:
cdinit subdir
And it will automatically git init
in that directory and move out of it.
You could also do a more complex solution using a function if you have a bunch of directories and want to git init
them with one command.
function cdinit() {
for arg in $@
do
cd $arg
git init
cd ..
done
}
You can then run this with:
cdinit subdir1 subdir2 subdir3
And it will do git init
in subdir1
, subdir2
, and subdir3
.
1@CraigMcQueen: not really.
$?
will contain the exit code of the last command that ran in the subshell. If you use the&&
variant (which you usually should), then you'll get the exit code of the first command that failed (or 0 if all went ok). – Mat – 2015-07-20T05:12:02.440I think the parentheses are optional – Francis.Beauchamp – 2016-05-05T13:10:39.373
11@Francis.Beauchamp: if you omit the parens, you'll be in the subdir after the command rather than back where you started. – Mat – 2016-05-05T13:19:46.743
How does one do this on Windows? – Karl Morrison – 2019-07-19T06:08:49.180
1And if you do need to set an environment variable or two, just add that as another command at the beginning. – Hippo – 2012-12-24T11:18:52.070