Notes

Write a Bash Function to Create a gruntfile.js for your project

Create a Gruntfile.js with starter code everytime you type gruntfile in the Terminal

Edit on GitHub
Bash Scripting
2 minutes

Here is how it works

Everyt time i type gruntfile in the Terminal, it creates a gruntfile.js for me in the folder i am in. The resulting gruntfile.js has the following template code:

 1module.exports = function (grunt) {
 2  grunt.initConfig({
 3    pkg: grunt.file.readJSON('package.json'),
 4
 5    // CONFIG
 6  })
 7
 8  // PLUGINS
 9  grunt.loadNpmTasks('')
10
11  // TASKS
12  grunt.registerTask('default', ['', ''])
13}

I can now add my Grunt config to it.

What i have done is create a function gruntfile for me and saved in my .bash_profile so it is available to me anywhere in the Terminal.

Here is the code

 1color_green='\033[92m'
 2color_red='\033[91m'
 3color_off='\033[0m'
 4
 5gruntfile() {
 6  if [ -e "gruntfile.js" ] ; then
 7    echo -e "${color_red}gruntfile.js already exists${color_off}"
 8
 9    if [ -e "Gruntfile.js" ] ; then
10      echo -e "${color_red}Gruntfile.js already exists${color_off}"
11    fi
12
13  else
14  echo -e "
15    module.exports = function(grunt) {
16      grunt.initConfig({
17        pkg: grunt.file.readJSON('package.json'),
18
19        // CONFIG
20
21        });
22
23        // PLUGINS
24        grunt.loadNpmTasks('');
25
26        // TASKS
27        grunt.registerTask('default', ['', '']);
28    };
29  " >> gruntfile.js
30
31  echo -e "${color_green}Gruntfile has been created${color_off}"
32  fi
33}

Copy this code to the bottom of your .bash_profile.

Quit and re-open the Terminal after you are done editing. Alternatively, you can also run source .bash_profile to load the changes you just made.

Notes

  • The echo command must be run with the -e flag to execute it as a command instead of just printing it out to the terminal.
  • Also, echo only seems to work if you wrap the statement in double quotes " ". It will not work with single quotes ' '
  • Since there is no simple way of checking case-insensitively if a file exists, i have added an if statement twice to check for both gruntfile.js and Gruntfile.js
  • I have added color coding so that it’ll show a red response if the file already exists and a green one if a file was succesfully created after running the function.

If this all seems too technical, you can just create a sublime text snippet for Grunt.

The purpose of writing this is to show the possibilities of what you can do with bash scripts and .bash_profile. For example, you can set up project templates and create your whole directory structure by typing new project. You can add a license to your project license files by typing license. And much more.

Related