Skip to content Skip to sidebar Skip to footer

How To Run A Shell Command From Grunt Task Function

I'm trying to move some icons in my app directory based on a function i have inside my Gruntfile.js. Would it be possible to do something like this? I've tried the following (going

Solution 1:

Yes, it's possible to achieve your requirement, however, when you invoke the grunt.task.run command inside your function (i.e. custom task) you need to provide a reference to a task to run.

If you define a separate Target, (Let's call call them copy_dev and copy_staging - as shown in the example below), for each cd ... && cp ... command in the grunt-exec Task it should work successfully.


Gruntfile.js

The following Gruntfile.js gist shows how this can be achieved:

module.exports = function (grunt) {

  grunt.loadNpmTasks('grunt-exec');

  grunt.initConfig({
    exec: {
      copy_dev: {
        cmd: 'cd app/lib/extras/res/icon/ios/dev && cp -a . ../'
      },
      copy_staging: {
        cmd: 'cd app/lib/extras/res/icon/ios/staging && cp -a . ../'
      }
    }
  });

  grunt.registerTask('setAppIcon', 'Task that sets the app icon', function() {
    var environment = process.env.NODE_ENV;

    // Exit early if NODE_ENV variable has not been set.if (!environment) {
      grunt.log.writeln(
        '\"setAppIcon\"" task failed - NODE_ENV has not been set.'['yellow']
      )
      return
    }

    if (environment.toLowerCase() == "development") {
      grunt.task.run('exec:copy_dev');
      grunt.log.writeln('>> Copying icons from \"dev\"...')
    } elseif (environment.toLowerCase() == "staging") {
      grunt.task.run('exec:copy_staging');
      grunt.log.writeln('>> Copying icons from \"staging\"...')
    }
  });

  grunt.registerTask('default', [ 'setAppIcon' ]);
};

Additional notes

Inside the custom task/function named setAppIcon we obtain the current node environment using nodes builtin process.env

When running $ grunt via your CLI (using the gist shown above), and assuming your process.env.NODE_ENV variable has not been set, or it has possibly been unset by running $ unset NODE_ENV, you will see the following message:

"setAppIcon"" task failed - NODE_ENV has not been set.

However, if the process.env.NODE_ENV variable has been set to either development or staging the files will be copied as expected.

For example running either of the following via your CLI will work successfully:

$ export NODE_ENV=development && grunt

or

$ export NODE_ENV=staging && grunt

You will also see either of the following messages logged to the console:

>> Copying icons from "dev"...

or

>> Copying icons from "staging"...

After process.env.NODE_ENV has been set to either development or staging then just running $ grunt via your CLI, will copy files according to which environment is set.

Post a Comment for "How To Run A Shell Command From Grunt Task Function"