gitgit-ls-files

How an I make `git ls-files` work in subdirectories?


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?


Solution

  • 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