Skip to content
Learning Outcomes
  • Understand the different script execution modes in Nextflow.
  • Learn how to define and use variables in script blocks.
  • Explore conditional scripting in Nextflow processes.
  • Discover how to integrate Nextflow and shell commands seamlessly.

Process Guide

Scripts

This section outlines the script execution modes available in Nextflow, which include Script, Shell, and Exec. Each mode determines how commands are executed in a process.

A. Script

By default, Groovy variables defined outside the script: block can still be modified after the script: block. Inside triple-quoted """ script blocks, you can reference these variables using Groovy string interpolation with the $ prefix (for example, $variableName or ${variableName}).

script:
def myGroovyVariable = "my params"
"""
STAR -o . ${indexPath} ${reads} ${myGroovyVariable}
"""

In the example above, ${myGroovyVariable} will be replaced by my params before execution. You can include any commands or scripts that are typically run in a terminal or BASH environment.

Add parameter

Example of a Complex Script Block

In more complex scenarios, Nextflow variables can be defined between the script: keyword and the opening triple double quotes:

script:
name = reads.toString() - '.fastq' // local scope for Nextflow variables

""" 
newPath="/mypath"   # Define BASH variable in local scope
STAR -o . \${newPath} ${name}  
"""

Note:

  • The newPath variable is defined within the BASH script, used in the STAR command as \${newPath}. Note the necessity of escaping BASH variables with backslashes in script blocks.
  • The name variable is established in Groovy's scope as a Nextflow variable, utilized in the STAR command as ${name}.

Conditional Scripts

You can employ conditional scripts with control statements like "if" and "switch." To indicate that all subsequent statements belong to a single code block, begin with the keyword script:. Here’s how it looks:

script:
name = reads.toString() - '.fastq'

if (mate == "pair") {
    """
    bowtie2 -x genome.index -1 ${reads.join(' -2 ')} -S ${name}_alignment.sam --un-conc ${name}_unalignedreads
    """
} else if (mate == "single") {
    """
    bowtie2 -x genome.index -U $reads -S ${name}_alignment.sam --un ${name}_unalignedreads
    """
}

Tip: The above example shows how to run Bowtie based on the status of the mate parameter, which you must include as an input. Choose between single or pair while running the pipeline to meet your requirements.

B. Exec

Nextflow also permits the execution of native code beyond system commands through the exec mode. To initiate exec mode, prepend an exec: block like so:

exec:
println "${genome}"

This allows for direct execution of code, without staging any files or starting any instance in cloud.