Converting hundreds of images, compressing logs or checking dozens of configuration files one at a time takes long when the machine has several cores. GNU Parallel runs one command per value of a list, several at a time, and prints the output of each job as one block, without mixing lines. It suits batch processing where each value is independent of the others.
xargs can also run calls in parallel with -P, but it groups arguments and lets the outputs mix. This page covers parallel alone: composing the command, setting the number of jobs and the order of the outputs, then spotting failures. Finding the files to process is covered in find.
What you will learn
- Run a command once per value of a list with
:::,::::or a pipe - Set the number of simultaneous jobs with
-jand the order of the outputs with-k - Compose the command with
{},{.},{/},{#}and read a file with columns using--colsep - Preview the commands with
--dry-run - Keep names that contain a newline whole with
find -print0and--null - Read the exit code of
paralleland the--joblogjournal - Stop a batch at the first failure with
--halt
Prerequisites
You know how to open a Linux terminal, create a folder and move into it with cd. You know echo, sleep and the exit code of a command ($?). Redirections and pipes (|, <) are used from the first examples. For the section on remote machines, you also need an SSH key already deployed on a server.
Installation
The package is called parallel on Debian and Ubuntu. On AlmaLinux 10, it comes from the EPEL repository, which is not in the base repositories: enable it first.
sudo apt install parallelsudo dnf install epel-release && sudo dnf install parallelThe outputs on this page come from GNU parallel 20240222 (Debian 13 package, two processors); parallel --version | head -1 prints your version. AlmaLinux 10 ships a newer version (20261022) which, on a terminal, prints a citation request after a few runs; the Debian and Ubuntu one does not. To silence it, run parallel --citation and type will cite.
Create the practice folder
All the examples run in ~/parallel-lab. The commands below create liste.txt (three names, one of which contains a space, used by the map), chemins.txt and d.csv to compose the commands, logs and noms for the full case and --null, and a conf folder with its script valider.sh for the second exercise. The file names use French words, which the commands keep: liste is "list", chemins "paths", mon fichier "my file", noms "names", valider "validate", journal "log" and nexistepas "does not exist".
mkdir ~/parallel-lab && cd ~/parallel-lab && {printf '%s\n' 'a.txt' 'mon fichier.txt' 'b.txt' > liste.txtprintf '%s\n' '/tmp/x/archive.tar.gz' '/srv/data/photo.jpg' > chemins.txtprintf '%s\n' 'a,1' 'b,2' 'c,3' > d.csvmkdir logs noms conffor n in 1 2 3; do seq 20000 > "logs/app $n.log"; donetouch 'noms/a b.txt' $'noms/e\nf.txt'printf 'port=80\n' > conf/web.confprintf 'debug=on\n' > conf/api.confprintf 'port=5432\n' > conf/db.confprintf 'debug=off\n' > conf/cache.confprintf 'port=8080\n' > conf/front.confprintf '#!/bin/sh\ngrep -q "^port=" "$1"\n' > valider.shchmod +x valider.sh}The braces group the commands behind the &&: they only run if mkdir ~/parallel-lab succeeds. If the folder already exists, nothing is written: delete the old one (section "Clean up the practice folder"). The paths in chemins.txt do not exist, which is enough for echo. One of the files in noms contains a newline in its name, which touch accepts.
The parallel command in detail
A parallel line is written in this order: the tuning options (-j, -k), the command to run with its {} marker, then the ::: separator followed by the values. Each value gives one job. The options go before the command, otherwise parallel passes them to that command. Read the line from left to right: each number points to the explanation of that piece.
Anatomy of the command
Syntaxparallel [options] command ::: values
parallel-j 2-kecho{}:::a b c -
parallelthe programIt runs several commands at the same time. -
-j 2the slotsoptionalThe number of simultaneous jobs. -
-kthe orderoptionalOutputs follow the order of the list. -
echothe commandThe one each job runs. -
{}the markeroptionalReplaced by the value, already protected. -
:::the separatorWhat follows is the list of values. -
a b cthe valuesOne job for each.
Outputa, b, c, in this order
Argument sources
The list of values can come from three places: written after :::, read from a file with ::::, or arriving on standard input. In all three cases, one job starts per value, and a file or a pipe is split at newlines, not at spaces. Without a {} marker, parallel adds the value at the end of the command.
parallel echo :::: liste.txtparallel echo < liste.txtparallel echo '[{}]' < liste.txta.txtmon fichier.txtb.txt[a.txt][mon fichier.txt][b.txt]The second command gives the same three lines as the first. Look at mon fichier.txt: it stays a single argument, whereas xargs cuts it in two (see "parallel or xargs?"). The {} marker sets where the value is inserted, here between brackets.
Placeholders: the heart of parallel
A placeholder is a marker replaced by the value of the job. Besides {}, parallel offers placeholders that split a path without calling basename or dirname.
| Placeholder | Meaning |
|---|---|
{} | The whole value |
{.} | The value without its extension |
{/} | The file name, without the folder |
{//} | The folder |
{/.} | The file name without extension |
{#} | The job number, starting at 1 |
parallel -k echo {}, {.}, {/}, {//}, {/.}, n{#} :::: chemins.txt/tmp/x/archive.tar.gz, /tmp/x/archive.tar, archive.tar.gz, /tmp/x, archive.tar, n1/srv/data/photo.jpg, /srv/data/photo, photo.jpg, /srv/data, photo, n2The -k option keeps the lines in the order of the list (see "Output order not guaranteed"). Each line is a job, each column a placeholder. Look at {.} on archive.tar.gz: it removes only the last extension and leaves archive.tar. The commas separate the columns in the display; a | in their place would be read by the shell as a pipe, and parallel echo '{} | {.}' :::: liste.txt fails with a: command not found (code 3).
Simulation mode
Before running rm, mv or convert on a list, --dry-run prints the commands that parallel would have run, without running any. Every value that contains a space is already protected between apostrophes. Placeholders are tested the same way, here with the .jpg to .png conversion of the list of paths.
parallel -k --dry-run cp {} {.}.bak :::: liste.txtparallel -k --dry-run convert {} {.}.png :::: chemins.txtcp a.txt a.bakcp 'mon fichier.txt' 'mon fichier'.bakcp b.txt b.bakconvert /tmp/x/archive.tar.gz /tmp/x/archive.tar.pngconvert /srv/data/photo.jpg /srv/data/photo.pngYou read one command per line of the list. Look at 'mon fichier'.bak: the space is protected, and {.} is glued to .bak. One line more or less signals an unexpected split: fix it before removing --dry-run.
Control the parallelism
-j N sets the number of simultaneous jobs. Without -j, parallel runs as many jobs as there are logical processors, the number that nproc returns (2 on the test machine). To see it, you need jobs that last: sleep 1 waits one second, and time gives the total duration on the real line.
time parallel -j1 sleep ::: 1 1time parallel -j2 sleep ::: 1 1time parallel sleep ::: 1 1time parallel -j2 sleep ::: 1 1 1 1real 0m2.124sreal 0m1.070sreal 0m1.078sreal 0m2.133sWith -j1, the two pauses follow each other: 2 seconds. With -j2, or with no option on a two-processor machine, they run together: 1 second. With four pauses and two slots, parallel starts two jobs, then one job per slot that frees up: 2 seconds. Too many simultaneous jobs saturate the processor, the memory or the disk: choose -j according to the resource that limits you, not according to the number of values.
Output order not guaranteed
parallel prints the output of a job when it ends, as one block. The order therefore follows the end of the jobs, not the order of the list: with parallel -j3 'sleep {}; echo fin {}' ::: 3 1 2, fin 1 is printed before fin 3. With -k (for keep order), the outputs follow the order of the list: a finished job waits until those before it have printed. With -j1, only one job runs at a time and the order of the list comes back by itself.
When a job writes several lines, --tag puts its value in front of each one: parallel --tag -k 'echo ligne1; echo ligne2 {}' ::: a b prints a and ligne1 separated by a tab, then a and ligne2 a, then the two lines of b, each job staying grouped.
How parallel runs the jobs, step by step
parallel takes a job from the list, starts it in a free slot, and prints its output when it ends. The map follows three jobs of different durations: sleep 3, sleep 1 and sleep 2, each followed by an echo.
Before you look at the map, predict the print order for parallel -j3 'sleep {}; echo fin {}' ::: 3 1 2. What does that order become with -k? What does -j1 give with three jobs, and how long does the batch take? Then check on the map: look at the "Jobs to run" area and the screen on the right.
Mental model
How parallel runs jobs
take a jobrun it in a free slotprint its output when it ends as long as jobs remain
Try Jobs to do
Run, wait, print
Elapsed time
$ parallel -j3 'sleep {}; echo fin {}' ::: 3 1 2
- The three jobs start together: there is a slot for each one.
- Job 1 ends: parallel prints its output.
- Job 2 ends: parallel prints its output.
- Job 3 ends: parallel prints its output.
- Three jobs in 3 seconds instead of 6.
What the animation shows
- One job per line: a name with a space stays whole.
- The display order is the order of completion, not the order of the list, except with
-k. - `-j` sets the number of slots. Without
-j, one slot per processor. - Outputs do not mix: each job is printed as one block.
Golden rules
Look before acting
--dry-run prints the commands without running them:
parallel --dry-run echo {} < liste.txtKeep the order when it matters
Add -k:
parallel -k echo {} < liste.txtEssential vocabulary
Build the command · what each job receives
{}- The value of the job
parallel -k echo {} < liste.txt→ 3 lines {.}- The value without its extension
parallel -k echo {.} < liste.txt→ a, mon fichier, b --colsep- One column of a file
echo a,1 | parallel --colsep , echo {1} vaut {2}→ a vaut 1 ::: :::- Two lists combined
parallel -k echo {1}{2} ::: a b ::: 1 2→ 4 combinations
Control the run · how many, in which order
--dry-run- Print without running
parallel -k --dry-run echo {} < liste.txt→ the commands, protected -k- The order of the list
parallel -j3 -k 'sleep {}; echo fin {}' ::: 3 1 2→ 3 1 2 --tag- Tell who wrote each line
parallel -k --tag echo salut ::: a b→ a then b before the line $?- The number of failures
parallel 'exit {}' ::: 0 1 5; echo $?→ 2 failures
Why does the batch last three seconds?
A colleague runs parallel sleep 1 ::: 1 2, expecting to wait one second, twice: for them, 1 2 only numbers the jobs. The batch feels long. Measure the duration, understand why, then write the command that does what they wanted for the values 1 and 2.
Measure the duration
Run the colleague's command preceded by time. Note the real line.
Read the commands that were built
Run the same line again with --dry-run in place of time. Compare the command of each job with what the colleague expected.
Fix the command
Write the command that waits 1 second for the first job and 2 seconds for the second, check it with --dry-run, then run it.
- time
- parallel --dry-run
A hint 1 / 1
Without a marker, parallel adds the value at the end of the command, after what you have already written.
I have tried: show the solution
time parallel sleep 1 ::: 1 2parallel --dry-run sleep 1 ::: 1 2parallel --dry-run 'sleep {}' ::: 1 2sleep 1 1sleep 1 2sleep 1sleep 2The first command prints real 0m3.063s. parallel added the value at the end: sleep 1 1 waits 2 seconds (1 + 1), sleep 1 2 waits 3 seconds (1 + 2), and both run together: 3 seconds for the batch. With {} in the command, the value replaces the marker: the jobs are sleep 1 and sleep 2, and the second does wait 2 seconds.
Handling files with spaces
parallel splits its input at newlines and protects each value before passing it to the shell. A name that contains a space, a semicolon or a $ therefore arrives as text, never as a command.
printf 'a;date\n' | parallel echo {}printf '$(id)\n' | parallel echo {}a;date$(id)a;date is printed as is: date was not run, and $(id) was not expanded. This protection falls if you write {} inside quotes in the command: parallel then pastes the protected value inside your quotes, and the shell interprets it.
printf '$(id)\n' | parallel 'echo "{}"''uid=1001(ansible) gid=1001(ansible) groups=1001(ansible),27(sudo)'The id command ran. With "echo '{}'", the value a;date runs date the same way. Never put quotes around {} in the command that parallel passes to the job's shell: parallel 'echo [{}]' gives [mon fichier.txt] for the value mon fichier.txt, with no risk. The apostrophes that wrap the whole command, as here, do not count: your shell removes them before parallel reads the command.
The only name that cuts the list is one that itself contains a newline. The noms folder holds one: e, a newline, then f.txt.
find noms -type f | sort | parallel -k echo '[{}]'find noms -type f -print0 | sort -z | parallel --null -k echo '[{}]'[f.txt][noms/a b.txt][noms/e][noms/a b.txt][noms/ef.txt]Without -print0, find separates its results with newlines: the file with the trapped name is cut into noms/e and f.txt. With -print0, find separates the paths with a null byte, which sort -z and parallel --null can read: the name stays whole, newline included. The sort makes the order identical on your machine; without it, the order of find varies.
Badly handled quotes
The protection applies to the values, not to the command you write. A ; written in the command is run by the shell that parallel starts for each job. Put the command between apostrophes so that the ; reaches parallel instead of being read by your shell.
parallel 'echo {}; date +fin' ::: xparallel -q echo '{};fin' ::: xxfinx;finThe first command runs echo then date in the same job. Without the apostrophes, parallel echo {}; date +fin ::: x is cut by your shell: date receives ::: and answers date: extra operand ‘:::’. The -q option (quote) passes special characters as is: the ; stays text, hence x;fin.
Quotes also decide when $(…) is evaluated. Between double quotes, your shell evaluates it before parallel; between apostrophes, each job evaluates it itself.
parallel "echo $(echo avant)" ::: xparallel 'echo $(echo pendant {})' ::: xavant xpendant xThe first $(…) does not know the value of the job: it runs once, beforehand, and parallel adds x at the end. The second receives {} replaced and runs inside each job. The words avant and pendant are French for "before" and "during".
Multi-column arguments
--colsep splits each line into columns, and {1}, {2} designate the first and the second. The file d.csv contains a,1, b,2 and c,3; {2} {1} swaps the columns, which is useful to pass a source then a destination to cp or mv.
parallel --colsep , echo {2} {1} < d.csv1 a2 b3 cThree lines, three jobs. The separator is a regular expression: printf 'a, 1\n' | parallel --colsep ', *' echo {1}-{2} prints a-1, the comma and its space counting as a single separator. With two ::: separators, parallel instead takes the product of the two lists, and --link pairs them one to one.
Error handling
The exit code of parallel is the number of jobs that failed. The shell puts it in $?, and exit {} is a command that ends with the value it receives.
parallel 'exit {}' ::: 0 1 0; echo $?parallel 'exit {}' ::: 0 1 5 7 0; echo $?parallel 'exit {}' ::: 0 0 0; echo $?130One failed job gives 1, three failed jobs give 3 (whatever their codes 1, 5 and 7), no failure gives 0. Unlike xargs, which returns 123 for "at least one call failed" without saying how many, parallel counts. The count is capped: 101 means "more than 100 failed jobs".
seq 100 | parallel false; echo $?seq 150 | parallel false; echo $?100101Find which jobs failed
The exit code says how many, not which ones. --joblog file writes a journal with one line per job.
parallel --joblog journal.txt 'exit {}' ::: 0 3 0cat journal.txtSeq Host Starttime JobRuntime Send Receive Exitval Signal Command1 : 1795610854.265 0.000 0 0 0 0 exit 02 : 1795610854.266 0.003 0 0 3 0 exit 33 : 1795610854.268 0.001 0 0 0 0 exit 0Look at the Exitval column: job 2 is the only one that is not 0, and the Command column repeats the exact command. The parallel command itself returned 1, a single failure. The Starttime dates will be your own. To keep only the useful columns, cut -f1,7,9 journal.txt prints Seq, Exitval and Command.
Once the cause is fixed, parallel --retry-failed --joblog journal.txt reads the journal and only reruns the jobs whose Exitval is not 0. The new lines are added at the end of the journal, without erasing the old ones.
Stop the batch at the first failure
--halt now,fail=1 stops parallel as soon as a job fails and kills those still running. Here are three jobs of 1, 5 and 5 seconds that all fail:
time parallel -j3 --halt now,fail=1 'sleep {}; echo fin {}; exit 1' ::: 1 5 5fin 1parallel: This job failed:sleep 1; echo fin 1; exit 1
real 0m1.072sThe batch stops at the first second, instead of waiting for the 5 seconds of the other two. For comparison, parallel -j3 'sleep {}; echo fin {}; exit 1' ::: 1 2 2 without --halt prints fin 1, fin 2, fin 2, lasts real 0m2.060s and returns 3.
With --halt, the exit code changes meaning: parallel --halt now,fail=1 'exit {}' ::: 0 5 0; echo $? prints parallel: This job failed:, exit 5, then 5, which is the code of the job and not the number of failures. now kills the running jobs; soon lets them finish and starts nothing more.
Which configurations have no port?
The conf folder contains five configuration files. The valider.sh script receives a file and exits with code 0 if the file contains a line that starts with port=, and with code 1 otherwise. Check the five files in parallel, keep a journal, find the ones that fail, then fix one and rerun only the failures.
Validate the five files
Run valider.sh on each file of conf ({} passes it; the shell expands conf/*.conf), with --joblog to journal.txt and the jobs in the order of the list. Then print the exit code of parallel.
Read the journal
Print the Seq, Exitval and Command columns of journal.txt and spot the jobs whose Exitval is not 0. Note the matching files.
Fix and rerun the failures
Add a port=1 line to api.conf, then rerun only the failed jobs of the journal. Read the journal again.
- parallel --joblog
- parallel --retry-failed
I have tried: show the solution
parallel -k --joblog journal.txt ./valider.sh {} ::: conf/*.conf; echo $?cut -f1,7,9 journal.txtprintf 'port=1\n' >> conf/api.conf; parallel --retry-failed --joblog journal.txt; cut -f1,7,9 journal.txtSeq Exitval Command1 1 ./valider.sh conf/api.conf2 1 ./valider.sh conf/cache.conf3 0 ./valider.sh conf/db.conf4 0 ./valider.sh conf/front.conf5 0 ./valider.sh conf/web.conf1 0 ./valider.sh conf/api.conf2 1 ./valider.sh conf/cache.confweb.conf, db.conf and front.conf contain port= and return 0. api.conf (debug=on) and cache.conf (debug=off) do not, and return 1. The exit code of parallel is therefore 2, the number of failures, and the first file in alphabetical order is api.conf. The rerun only redid jobs 1 and 2 and added two lines: api.conf is now 0, cache.conf still fails.
Progress tracking
--bar prints a progress bar, and --eta an estimate of the remaining time. They write to standard error, not to standard output: the results of the jobs stay clean, but a script that captures standard error finds terminal control codes in it. Use them in an interactive terminal, never in a scheduled task.
Run on remote machines
-S (--sshlogin) spreads the jobs over machines reached by SSH. parallel does not need to be installed on the remote machine. Use a key: without a usable key, the connection fails with Permission denied (publickey,keyboard-interactive) and counts as a failure; an ssh configured with a password may ask for it on the terminal, which does not suit a batch. This command needs a server; replace admin@srv with yours.
parallel -k -S admin@srv 'echo {}; hostname' ::: 1 21lpg-ubuntu.lab2lpg-ubuntu.labhostname prints the name of the server: the jobs ran there.
Full case: compress log files
The logs folder contains three .log files whose names have a space. The sequence is the one of bulk processing: preview, act, check, roll back.
parallel -k --dry-run gzip {} ::: logs/*.logparallel gzip {} ::: logs/*.log; ls -1 logsparallel gunzip {} ::: logs/*.gz; ls -1 logsgzip 'logs/app 1.log'gzip 'logs/app 2.log'gzip 'logs/app 3.log'app 1.log.gzapp 2.log.gzapp 3.log.gzapp 1.logapp 2.logapp 3.logThe shell expands logs/*.log into three names, and --dry-run shows that each one is protected by apostrophes. gzip replaces each .log with a .log.gz: ls then shows only the archives. gunzip restores the originals.
parallel or xargs?
xargs is present on every distribution, parallel has to be installed: on machines you do not control, xargs is the safe choice. The outputs below are those of GNU findutils 4.10.0 and of parallel on the same list.
xargs -n1 echo < liste.txtxargs -d "\n" -n1 echo < liste.txtparallel echo :::: liste.txta.txtmonfichier.txtb.txta.txtmon fichier.txtb.txtxargs cuts at spaces unless you give it -d "\n": mon fichier.txt becomes two arguments. parallel cuts at newlines by default. With xargs -P, the lines of two calls running together can interleave; with parallel, each job prints as one block. Choose xargs for a command that accepts several arguments (rm, grep), and parallel for one job per value whose outputs you want grouped and whose failures you want counted.
Troubleshooting
When the result is not what you expected, run the same line again with --dry-run: you read the commands that parallel built.
| Symptom | Cause | Solution |
|---|---|---|
parallel: Error: Cannot open `nexistepas.txt': No such file or directory (code 255) | The file behind :::: does not exist | Fix the path |
nexistepascmd: command not found, code 1 | The command is not installed or misspelled | Check the command of each job with command -v |
parallel echo -k ::: a b prints -k a and -k b | The option is after the command: parallel passes it to it | Put the parallel options before the command |
Input is read from the terminal and nothing happens | No list: no :::, no ::::, no pipe | Add the list, or press Ctrl-D to quit |
| A value is run as a command | {} is inside quotes in the command | Write {} without quotes |
| The outputs arrive out of order | Each output is printed when its job ends | Add -k |
Clean up the practice folder
When you are done, delete the practice folder.
cd ~rm -r ~/parallel-labKey points
parallel command ::: valuesruns one job per value, several at a time;::::reads a file and a pipe also supplies the list. Without{}, the value is added at the end of the command.-j Nsets the number of simultaneous jobs; without-j, it is the number of processors given bynproc.- Outputs are printed at the end of each job, as one block;
-kputs them back in the order of the list,--tagputs the value in front of each line. - Values are protected, unless
{}is inside quotes in the command.--dry-runshows the commands without running them. - The exit code is the number of failed jobs (101 at most);
--joblogsays which ones,--retry-failedreruns only those, and--halt now,fail=1stops the batch at the first. --nullwithfind -print0keeps names that contain a newline whole;--colsepsplits each line into columns.
Knowledge check
Check that the essentials of this guide are acquired. The questions only cover what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: find: search for files by name, size and date
A new full quiz with random questions
Work again only on the questions you missed