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_deleted
retrieves a list of deleted files usinggit ls-files --deleted
. - If there are any deleted files, the function adds and commits them using
git add
andgit 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
git ls-files
documentation: https://git-scm.com/docs/git-ls-filesgit add
documentation: https://git-scm.com/docs/git-addgit commit
documentation: https://git-scm.com/docs/git-commit