Finding unused Scss variables

With any Sass project variables play an important part but they can get out of control and managing them can be difficult at times. During development we are creating new ones, removing them or in some cases not finding a need for them.

It’s good practice to ensure our codebase is clean and maintainable, one method towards this is by removing unused Scss variables. This can be achieved by using a simple bash script:

VAR_NAME_CHARS='A-Za-z0-9_-'
find "$1" -type f -name "*.scss" -exec grep -o "\$[$VAR_NAME_CHARS]*" {} ';' | sort | uniq -u

How to use

1. Create a file named unused-variables.sh in the parent folder of your Scss files
2. Copy and paste the contents of the above script into the file
3. Open the parent folder of scss in your command prompt
4. Run the following command to make the file executable:

chmod +x ./unused-variables.sh

5. Run the script:

./unused-variables.sh ./scss

It will then display a list of the unused variables within the command prompt. You can then use this information to remove the declaration from your Scss file.

There are multiple versions of this bash script including ones that cater for the Less pre-processor. The original script being used can be found here.