2

I want to run git ls-file --modified to obtain a list of files with unstaged changes. I was surprised to find that it works in the root directory, but not in any subdirectory, where it only prints files from the subdirectory (in contrast to git status, for instance).

Steps to reproduce:

mkdir repo
cd repo
git init
touch file.txt
git add file.txt 
mkdir subdirectory
echo "foo" >> file.txt    # file now has unstaged changes
git ls-files --modified   # This prints 'file.txt'
cd subdirectory/
git ls-files --modified   # This prints nothing

How can I change git's behaviour here?

Chris Maes
  • 26,426
  • 4
  • 84
  • 113
oarfish
  • 3,240
  • 4
  • 25
  • 54

1 Answers1

3

By default many git commands run with respect to your current working directory (git status, ls-files,...).

You can use -C:

git -C ../ ls-files --modified

if you want the command to run with respect to the git 'toplevel', you could run:

git -C $(git rev-parse --show-toplevel) ls-files --modified

from the man page of git:

   -C <path>
       Run as if git was started in <path> instead of the current working directory. When multiple -C options are given, each subsequent

EDIT It also depends what kind of output you want, as @phd not. See below commands and output to understand the different options and their output:

> git -C ../ ls-files --modified
file.txt
> git -C $(git rev-parse --show-toplevel) ls-files --modified # wrt git toplevel no matter how deep you are in the tree
file.txt
> git ls-files --modified ../
../file.txt
> git ls-files --modified $(git rev-parse --show-cdup) # wrt git toplevel no matter how deep you are in the tree
../file.txt
Chris Maes
  • 26,426
  • 4
  • 84
  • 113
  • 1
    The disadvantage of `git -C` in this case is that `git ls-files` shows modified files related to the root, not to the current directory. IMO a better way is `git ls-files --modified $(git rev-parse --show-cdup)`. – phd May 15 '19 at 11:00
  • @phd: thanks for the tip; I added this to my answer. – Chris Maes May 16 '19 at 06:40