Magento 2: How to delete all cached and generated files

The script need to be executed in Magento 2 root folder.

It deletes all the contents of var subfolder except var/session subfolder and except the.htaccess file

It deletes all the contents of pub/static subfolder except the.htaccess file

find var/* -type f -or -type d | grep -v 'session' | xargs rm -rf && \
rm -rf pub/static/*