Skip to content

Instantly share code, notes, and snippets.

@wezm
Created August 27, 2011 09:25
Show Gist options
  • Save wezm/1175182 to your computer and use it in GitHub Desktop.
Save wezm/1175182 to your computer and use it in GitHub Desktop.
Strip trailing whitespace in modified files tracked by git
#!/bin/sh
git ls-files --modified '*.[hm]' | xargs sed -i '.bak' 's/[[:space:]]*$//'
@fly2never
Copy link

I think NULL check will be better

FILE_PATH=`git ls-files --modified '*.[hm]'`
if [ -n "$FILE_PATH" ]
then
/usr/bin/sed -i '.bak' 's/[[:space:]]*$//' "$FILE_PATH"
fi

@wezm
Copy link
Author

wezm commented May 1, 2012

Good point, not sure why that's never been a problem I've run into. Updated as per your suggestion.

@jakeboxer
Copy link

When I ran this on an unmodified project generated from the "Master-Detail Application" template, I got the following error:

sed: projectdirectory/AppDelegate.h
projectdirectory/AppDelegate.m
projectdirectory/DetailViewController.h
projectdirectory/DetailViewController.m
projectdirectory/MasterViewController.m: No such file or directory

When I removed the quotes from around $modified_files in the sed command, it worked. My working version looks like this:

#!/bin/sh

modified_files=`git ls-files --modified '*.[hm]'`
if [[ -n "$modified_files" ]]; then
  sed -i '.bak' 's/[[:space:]]*$//' $modified_files
fi

Not sure if there was something weird on my setup or what, but that's what worked for me.

@wezm
Copy link
Author

wezm commented Jul 29, 2012

I started getting this problem too. It happens when the files aren't in the top level of the project. I've come up with a shorter, better script as a result. Gist, updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment