How to Git Commit all Deleted files with Bash

The aim of this pageđź“ť is to explain how to modify a function to handle multiple files in a variable, based on the particular example of a broken commit_deleted function in a Git repository.

Pavol Kutaj
1 min readJan 22, 2024

Originally, I had a broken function:

function commit_deleted {
deleted_files=$(git ls-files --deleted)
if [[ -n "$deleted_files" ]]; then
git add "$deleted_files"
git commit -m "deleted"
fi
}

Explanation

Here is an in-depth explanation of how to modify the function to handle multiple files:

  • The original function commit_deleted retrieves a list of deleted files using git ls-files --deleted.
  • If there are any deleted files, the function adds and commits them using git add and git commit.
  • However, the original function assumes that there is only one deleted file in the $deleted_files variable.

To modify the function to handle multiple files, we can make the following changes:

  • Set the internal field separator (IFS) to a newline character ($'\n') to ensure that each file in $deleted_files is treated as a separate item in the loop.
  • Use a for loop to iterate over each file in $deleted_files.
  • Add each file individually using git add.
  • Finally, commit the changes with the message “deleted” using git commit -m "deleted".

Here is the fixed function:

function commit_deleted {
deleted_files=$(git ls-files --deleted)
if [[ -n "$deleted_files" ]]; then
IFS=$'\n'
for file in $deleted_files; do
git add "$file"
done
git commit -m "deleted"
fi
}

LINKS

--

--

Pavol Kutaj
Pavol Kutaj

Written by Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com

No responses yet