Imagine you’re working on a project where you need to download many files and store them in a specific directory structure. Before downloading the files, you want to ensure that the target directory exists. If it doesn’t, you create it. If it does, you simply copy the existing directory to the output location.
params.output_dir = "./results"
process makedir {
publishDir "${params.output_dir}/", mode: 'copy', overwrite: false
output:
path "newdir", emit: reference_fasta
script:
// Resolve the absolute path of the output directory
String absOutputDir = file(params.output_dir).toAbsolutePath().toString()
String targetFile = "${absOutputDir}/newdir"
if (!file(targetFile).exists()) {
"""
mkdir newdir
"""
} else {
"""
echo "directory already exists. Copying to output directory."
echo "absolute path : $absOutputDir"
echo "target path : $targetFile"
cp -r "${targetFile}" newdir
"""
}
}
workflow {
makedir()
}
case non existing directory:
$ nextflow run makedir.nf
Launching `makedir.nf` [pedantic_galileo] DSL2 - revision: 21e8d35aad
executor > local (1)
[33/7d1734] process > makedir [100%] 1 of 1 ✔
$ tree
.
├── makedir.nf
├── results
│ └── newdir
└── work
└── 33
└── 7d1734ec6d63226811a47161d58ff7
└── newdir
case directory exists : If you run the script again, you’ll see that it detects the existing directory and copies it:
$ nextflow run makedir.nf
Launching `makedir.nf` [shrivelled_austin] DSL2 - revision: 21e8d35aad
executor > local (1)
[b8/6b399a] process > makedir [100%] 1 of 1 ✔
$ cat work/b8/6b399a999c79e57e8208225833dbeb/.command.out
directory already exists. Copying to output directory.
absolute path : /home/firas/post/results
target path : /home/firas/post/results/newdir
$ tree
.
├── makedir.nf
├── results
│ └── newdir
└── work
├── 33
│ └── 7d1734ec6d63226811a47161d58ff7
│ └── newdir
└── b8
└── 6b399a999c79e57e8208225833dbeb
└── newdir