Run parametrized task using grunt.task.run(taskname)

I did stackoverflow search and looked at Grunt API docs but couldn't find a way to run a parametrized task using grunt.task.run(taskname).



I have a simple task which accepts a parameter and prints the message on console:



grunt.registerTask('hello', 'greeting task', function(name) {
if(!name || !name.length)
grunt.warn('you need to provide a name');

console.log('hello ' + name + '!');

});


I call the above task using below task which validates the task and if task exists then it runs it:



 grunt.registerTask('validateandruntask', 'if task available then run given  task', function(taskname) {
if(!taskname || !taskname.length) {
grunt.warn('task name is needed to run this task');
}

if(!grunt.task.exists(taskname)) {
grunt.log.writeln('this task does not exist!');
} else {
grunt.log.writeln(taskname + ' exists. Going to run this task');
grunt.task.run(taskname);
}

});


Now from command line, I am passing 'hello' task as parameter to 'validateandruntask' but I am not been able to pass the parameter to 'hello' task from command line:



This is what I tried on command line but it didn't work:



grunt validateandruntask:hello=foo



grunt validateandruntask:hello:param=name



Answers

First thing, the way to pass an arg through the command line is to use :.
For example to call hello directly:



grunt hello:you


To call it with multiple arguments, just separate them by :, like



grunt hello:mister:president


And to use these multiple arguments in the task, you do the same as plain Javascript: use arguments (all details here):



grunt.registerTask('hello', 'greeting task', function(name) {
if(!name || !name.length)
grunt.warn('you need to provide a name');
// unfortunately arguments is not an array,
// we need to convert it to use array methods like join()
var args = Array.prototype.slice.call(arguments);
var greet = 'hello ' + args.join(' ') + '!';
console.log(greet);
});


Then you want to call grunt validateandruntask:hello:mister:president, and modify your code to handle the variable parameters as well:



grunt.registerTask('validateandruntask', 'if task available then run given  task', function(taskname) {
if(!taskname || !taskname.length) {
grunt.fail.fatal('task name is needed to run this task');
}

var taskToCall = taskname;
for(var i = 1; i < arguments.length; i++) {
taskToCall += ':' + arguments[i];
}
console.log(taskToCall);

if(!grunt.task.exists(taskname)) {
grunt.log.writeln('this task does not exist!');
} else {
grunt.log.writeln(taskname + ' exists. Going to run this task');
grunt.task.run(taskToCall);
}
});