How to pass command line arguments to a rake task

rake task with arguments and environment
rake task arguments array
rake task invoke with arguments
rake task optional arguments
rake task multiple arguments
rake task environment
rake arguments command line
rspec rake task arguments

I have a rake task that needs to insert a value into multiple databases.

I'd like to pass this value into the rake task from the command line, or from another rake task.

How can I do this?

options and dependencies need to be inside arrays:

namespace :thing do
  desc "it does a thing"
  task :work, [:option, :foo, :bar] do |task, args|
    puts "work", args

  task :another, [:option, :foo, :bar] do |task, args|
    puts "another #{args}"
    Rake::Task["thing:work"].invoke(args[:option], args[:foo], args[:bar])
    # or splat the args
    # Rake::Task["thing:work"].invoke(*args)



rake thing:work[1,2,3]
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

rake thing:another[1,2,3]
=> another {:option=>"1", :foo=>"2", :bar=>"3"}
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

NOTE: variable task is the the task object, not very helpful unless you know/care about Rake internals.


If running the task from rails, its best to preload the environment by adding => [:environment] which is a way to setup dependent tasks.

  task :work, [:option, :foo, :bar] => [:environment] do |task, args|
    puts "work", args

How To Use Arguments In a Rake Task, You can write Rake tasks that accept arguments, called like this: rake tweets: send[cpytel]. You define the rask task like this: namespace :tweets� This feature isn't limited to a single argument. In fact, I can pass as many as I want: task :call, :response, :repeat do |t, args| response = args[:response] || 'Task' repeat = (args[:repeat] || 1).to_i puts "When I say Rake, you say '#{response}'!" repeat.times do sleep 1 puts "Rake!" sleep 1 puts "#{response}!" end end

You can specify formal arguments in rake by adding symbol arguments to the task call. For example:

require 'rake'

task :my_task, [:arg1, :arg2] do |t, args|
  puts "Args were: #{args} of class #{args.class}"
  puts "arg1 was: '#{args[:arg1]}' of class #{args[:arg1].class}"
  puts "arg2 was: '#{args[:arg2]}' of class #{args[:arg2].class}"

task :invoke_my_task do
  Rake.application.invoke_task("my_task[1, 2]")

# or if you prefer this syntax...
task :invoke_my_task_2 do
  Rake::Task[:my_task].invoke(3, 4)

# a task with prerequisites passes its 
# arguments to it prerequisites
task :with_prerequisite, [:arg1, :arg2] => :my_task #<- name of prerequisite task

# to specify default values, 
# we take advantage of args being a Rake::TaskArguments object
task :with_defaults, :arg1, :arg2 do |t, args|
  args.with_defaults(:arg1 => :default_1, :arg2 => :default_2)
  puts "Args with defaults were: #{args}"

Then, from the command line:

> rake my_task[1,false]
Args were: {:arg1=>"1", :arg2=>"false"} of class Rake::TaskArguments
arg1 was: '1' of class String
arg2 was: 'false' of class String

> rake "my_task[1, 2]"
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task_2
Args were: {:arg1=>3, :arg2=>4}

> rake with_prerequisite[5,6]
Args were: {:arg1=>"5", :arg2=>"6"}

> rake with_defaults
Args with defaults were: {:arg1=>:default_1, :arg2=>:default_2}

> rake with_defaults['x','y']
Args with defaults were: {:arg1=>"x", :arg2=>"y"}

As demonstrated in the second example, if you want to use spaces, the quotes around the target name are necessary to keep the shell from splitting up the arguments at the space.

Looking at the code in rake.rb, it appears that rake does not parse task strings to extract arguments for prerequisites, so you can't do task :t1 => "dep[1,2]". The only way to specify different arguments for a prerequisite would be to invoke it explicitly within the dependent task action, as in :invoke_my_task and :invoke_my_task_2.

Note that some shells (like zsh) require you to escape the brackets: rake my_task\['arg1'\]

4 Ways to Pass Arguments to a Rake Task, Always googling and forgetting how to pass arguments to rake tasks? You need brackets on the command line and you need to know the� When you pass in arguments to rake tasks, you can require the environment using the :needs option. For example: desc "Testing environment and variables" task :hello, :message, :needs => :environment do |t, args| args.with_defaults(:message => "Thanks for logging on") puts "Hello #{}. #{args.message}" end

In addition to answer by kch (I didn't find how to leave a comment to that, sorry):

You don't have to specify variables as ENV variables before the rake command. You can just set them as usual command line parameters like that:

rake mytask var=foo

and access those from your rake file as ENV variables like such:

p ENV['var'] # => "foo"

Rake: Task Arguments � Jacob Swanner, There are times when we want to pass variable data to our tasks; whether it's to pass variable data to Rake tasks – and this is how Rails' Rake tasks do it. from the third task, and the second line comes from the fourth task. task :say_hello do # ARGV contains the name of the rake task and all of the arguments. # Remove/shift the first element, i.e. the task name. ARGV.shift # Use the arguments puts 'Hello arguments:', ARGV # By default, rake considers each 'argument' to be the name of an actual task. # It will try to invoke each one as a task.

If you want to pass named arguments (e.g. with standard OptionParser) you could use something like this:

$ rake user:create -- --user --pass 123

note the --, that's necessary for bypassing standard Rake arguments. Should work with Rake 0.9.x, <= 10.3.x.

Newer Rake has changed its parsing of --, and now you have to make sure it's not passed to the OptionParser#parse method, for example with parser.parse!(ARGV[2..-1])

require 'rake'
require 'optparse'
# Rake task for creating an account

namespace :user do |args|
  desc 'Creates user account with given credentials: rake user:create'
  # environment is required to have access to Rails models
  task :create do
    options = {} do |opts|
      opts.banner = "Usage: rake user:create [options]"
      opts.on("-u", "--user {username}","User's email address", String) do |user|
        options[:user] = user
      opts.on("-p", "--pass {password}","User's password", String) do |pass|
        options[:pass] = pass

    puts "creating user account..."
    u =
    u[:email] = options[:user]
    u[:password] = options[:pass]
    # with some DB layer like ActiveRecord:
    # user =;!
    puts "user: " + u.to_s
    puts "account created."
    exit 0

exit at the end will make sure that the extra arguments won't be interpreted as Rake task.

Also the shortcut for arguments should work:

 rake user:create -- -u -p 123

When rake scripts look like this, maybe it's time to look for another tool that would allow this just out of box.

Passing parameters to Rake tasks (Example), Ever wonder how you can pass parameters to a rake task from the command line, well here is a quick tip on doing so. Let's say we have a Rake� How do you pass arguments to a rake task in RubyMine 3&period;0&quest; The situation I have a rake task similar to desc "A rake Task" task :give_me_gold, [:quantity,:quality] => :environment do |task, args| . end I am aware from the commandline you type rake give_me_gold[10,24] to pass parameters to the rake

I've found the answer from these two websites: Net Maniac and Aimred.

You need to have version > 0.8 of rake to use this technique

The normal rake task description is this:

desc 'Task Description'
task :task_name => [:depends_on_taskA, :depends_on_taskB] do
  #interesting things

To pass arguments, do three things:

  1. Add the argument names after the task name, separated by commas.
  2. Put the dependencies at the end using :needs => [...]
  3. Place |t, args| after the do. (t is the object for this task)

To access the arguments in the script, use args.arg_name

desc 'Takes arguments task'
task :task_name, :display_value, :display_times, :needs => [:depends_on_taskA, :depends_on_taskB] do |t, args|
  args.display_times.to_i.times do
    puts args.display_value

To call this task from the command line, pass it the arguments in []s

rake task_name['Hello',4]

will output


and if you want to call this task from another task, and pass it arguments, use invoke

task :caller do
  puts 'In Caller'

then the command

rake caller

will output

In Caller

I haven't found a way to pass arguments as part of a dependency, as the following code breaks:

task :caller => :task_name['hi',2]' do
   puts 'In Caller'

Rake Task with an Arbitrary Amount of Arguments, I'm currently working on a rake task where I need to pass in an arbitrary Unlike command line bash scripts or even calling a ruby script with� To call this task from the command line, pass it the arguments in []s. rake task_name['Hello',4] will output. Hello Hello Hello Hello and if you want to call this task from another task, and pass it arguments, use invoke. task :caller do puts 'In Caller' Rake::Task[:task_name].invoke('hi',2) end then the command. rake caller will output. In

Task Arguments And Rakefile Parameters, Rake tasks are a convenient method to automate repeating tasks and also make them available via the command line. Oftentimes these tasks� Passing rake task arguments to the `rspec` command via `rspec_opts` Default options with passing spec (prints command and exit status is 0)

Rake Tasks With Parameters, Passing named arguments to Ruby Rake tasks using docopt for data science as if the input to the task was provided on the command line. self.execute_rake ("stats", aggregate, parameters) Basically, we construct a list of arguments that emulates as if the input to the task was provided on the command line. We then call the other rake task using the following helper function: # Helper method for invoking and re-enabling rake tasks.

Passing named arguments to Rake tasks using docopt for data , Should it then get the first command line argument. explicitly passing values directly to the tasks that need them. then execute that task from the command line with gulp doSomething. Tasks can be as basic or complex as you like and include further sub-tasks. However, it’s not possible to pass arguments on

  • rakefile rdoc
  • Docs have been mirrored by SeattleRb.
  • Can you please change the accepted answer to the one from @BlairAnderson, as the accepted answer is very much out of date now. This question appears high on Google for this topic!
  • Also, make sure you don't use spaces between the arguments. E.g don't do this: rake thing:work[1, 2, 3] as it won't work and you'll get an error Don't know how to build task
  • Also, make sure you enclose the argument in string. e.g from your command line run the rake task like so rake thing:work'[1,2,3]'
  • Unfortuanely, zsh can not parse the call correctly, you need type the command on zsh like this: rake thing:work\[1,2,3\], or this rake 'thing:work[1,2,3]'
  • @sakurashinken you can remove the :environment symbol from your task. rails applications have an :environment task...
  • Instead of having a note to explain that t means task, why not just use task as the param name?
  • To invoke a task within a namespace simpy do: Rake::Task['namespace:task'].invoke
  • That's a separate question, Igoru, but the reason your call to invoke only runs once is that rake is dependency-oriented, so it will only execute a task if it is needed. For generic tasks that means if it hasn't already run. To explicitly execute a task regardless of its dependencies or if it is needed, call execute instead of invoke.
  • Note: According to rake, this syntax for accepting variables in tasks is deprecated: WARNING: 'task :t, arg, :needs => [deps]' is deprecated. Please use 'task :t, [args] => [deps]' instead.