git init, add, commit from a different directory

6.4k views Asked by At

I am writing a Lua script that creates a directory, creates some files inside of it and initializes git, adding those files to it and finally committing everything. However there's no way to use cd from inside Lua (you can, but it won't have effect), so I wonder if it's possible to git init a directory, git add some files and finally git commit -a -m "message", all while the working directory is the directory above the desired directory.

Edit: -C works, thanks everyone. For anyone wondering, in Lua, cd "resets" after the call to os.execute ends. So, os.execute("cd mydir"); os.execute("git init"); won't work as expected. To get it to work, use os.execute("cd mydir; git init;");.

2

There are 2 answers

0
Randy Leberknight On BEST ANSWER

By following the hint in the comments about -C I did:

git init newStuff
Initialized empty Git repository in c:/fw/git/initTest/newStuff/.git/

to make the git repo in dir newStuff (which I had already created)

Then I added two files to newStuff, and from it's parent using using -C

git -C newStuff/ status
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        new1
        new2

nothing added to commit but untracked files present (use "git add" to track)

I see the new files. Now add and commit them:

git -C newStuff/ add .
git -C newStuff/ status
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

        new file:   new1
        new file:   new2

git -C newStuff/ commit -m"initial"
[master (root-commit) bfe387b] initial
 2 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 new1
 create mode 100644 new2
0
vchenin On

Example on shell:

#!/bin/sh
dirPath=some/dir/path
mkdir -p $dirPath
touch $dirPath/newFile
git init $dirPath
git -C $dirPath add .
git -C $dirPath commit -a -m "Initial commit"
git -C $dirPath log