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.
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_deletedretrieves a list of deleted files usinggit ls-files --deleted. - If there are any deleted files, the function adds and commits them using
git addandgit commit. - However, the original function assumes that there is only one deleted file in the
$deleted_filesvariable.
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_filesis treated as a separate item in the loop. - Use a
forloop 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
git ls-filesdocumentation: https://git-scm.com/docs/git-ls-filesgit adddocumentation: https://git-scm.com/docs/git-addgit commitdocumentation: https://git-scm.com/docs/git-commit
