Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

GNU parallel - xargs on steroids

News  Parallel command execution Recommended Links Options

Examples

Reference Unix Xargs
pssh Slurping Shells Pipes AWK Perl Regex
find uniq cut tee History Humor Etc

The write-up below is based on parallel man page

Parallel is a Perl script written by Ole Tange that extends and improves capabilities of xargs.  Unlike xargs,   parallel can then split the input and pipe it into commands in parallel. Hence the name.  See O. Tange (2011):  Parallel - The Command-Line Power Tool, ;login: The USENIX Magazine, February 2011:42-47.

It can be used as a Slurping tool.

Parallel is written in Perl, and use several standard Perl modules such as Getopt::Long, IPC::Open3, Symbol, IO::File, POSIX, and File::Temp. For remote usage it also uses rsync with ssh.

If you use xargs and tee today you will find  parallel very easy to use as  parallel is written to have the same options as xargs. If you write loops in shell, you will find  parallel may be able to replace most of the loops and make them run faster by running several jobs in parallel.

Parallel makes sure output from the commands is the same output as you would get had you run the commands sequentially. This makes it possible to use output from  parallel as input for other programs.\

For each line of input  parallel will execute command with the line as arguments. If no command is given, the line of input is executed. Several lines will be run in parallel.  parallel can often be used as a substitute for xargs or cat | bash.

The most interesting part of parallel is that it allow ssh login via option --sshlogin (or -S).  In this case ssh logging must not require a password.

Transferring Files

If your servers are not sharing storage (using NFS or something similar), you often need to transfer the files to be processed to the remote computers and the results back to the local computer.

To transfer a file to a remote computer, you will use --transfer:

parallel -S .. --transfer gzip ‘< {} | wc -c’ ::: *.txt

Here we transfer each of the .txt files to the remote servers, compress them, and count how many bytes they now take up.

After a transfer you often will want to remove the transferred file from the remote computers.--cleanup does that for you:

parallel -S .. --transfer --cleanup gzip ‘< {} | wc -c’ ::: *.txt

When processing files the result is often a file that you want copied back, after which the transferred and the result file should be removed from the remote computers:

parallel -S .. --transfer --return {.}.bz2 --cleanup zcat ‘< {} | bzip2 >{.}.bz2’ ::: *.gz

Here the .gz files will be transferred and then recompressed using zcat and bzip2.The resulting .bz2 file is transferred back, and the .gz and the .bz2 files are removed from the remote computers.The combination --transfer --cleanup --return foo is used so often that it has its own abbreviation: --trc foo.

You can specify multiple --trc if your command generates multiple result files.

GNU Parallel will try to detect the number of cores on remote computers and run one job per CPU core even if the computers have different number of CPU cores:

parallel -S .. --trc {.}.bz2 zcat ‘< {} | bzip2 >{.}.bz2’ ::: *.gz

Before looking at the options you may want to check out the EXAMPLEs after the list of options. That will give you an idea of what  parallel is capable of.

You can also watch the intro video for a quick introduction: http://tinyogg.com/watch/TORaR/ http://tinyogg.com/watch/hfxKj/ and http://tinyogg.com/watch/YQuXd/ or http://www.youtube.com/watch?v=OpaiGYxkSuQ and http://www.youtube.com/watch?v=1ntxT-47VPA

parallel [options] [command [arguments]] < 
list_of_arguments

parallel [options] [command [arguments]] (
::: arguments | :::: argfile(s) ) ...
parallel --semaphore [options] command

#!/usr/bin/parallel --shebang [options] [command [arguments]]

Options:

command
Command to execute. If command or the following arguments contain {} every instance will be substituted with the input line.

If command is given,  parallel will behave similar to xargs. If command is not given  parallel will behave similar to cat | sh.

The command must be an executable, a script or a composed command: an alias or a function will not work (see why http://www.perlmonks.org/index.pl?node_id=484296).

{}
Input line. This is the default replacement string and will normally be used for putting the argument in the command line. It can be changed using option -I.
{.}
Input line without extension. This is a specialized replacement string with the extension removed. If the input line contains . after the last / the last . till the end of the string will be removed and {.} will be replaced with the remaining. E.g. foo.jpg becomes foo, subdir/foo.jpg becomes subdir/foo, sub.dir/foo.jpg becomes sub.dir/foo, sub.dir/bar remains sub.dir/bar. If the input line does not contain . it will remain unchanged.

{.} can be used the same places as {}. The replacement string {.} can be changed with -U.

{/}
Basename of input line. This is a specialized replacement string with the directory part removed.

{/} can be used the same places as {}. The replacement string {/} can be changed with --basenamereplace.

{//} (alpha testing)
Dirname of input line. This is a specialized replacement string containing the dir of the input. See dirname(1).

{//} can be used the same places as {}. The replacement string {//} can be changed with --dirnamereplace.

{/.}
Basename of input line without extension. This is a specialized replacement string with the directory and extension part removed. It is a combination of {/} and {.}.

{/.} can be used the same places as {}. The replacement string {/.} can be changed with --basenameextensionreplace.

{#} (beta testing)
Sequence number of the job to run. The same as $PARALLEL_SEQ.

The replacement string {#} can be changed with --seqreplace.

{n}
Argument from input source n or the n'th argument. See -a and -N.

{n} can be used the same places as {}.

{n.}
Argument from input source n or the n'th argument without extension. It is a combination of {n} and {.}.

{n.} can be used the same places as {n}.

{n/}
Basename of argument from input source n or the n'th argument. It is a combination of {n} and {/}. See -a and -N.

{n/} can be used the same places as {n}.

{n/.}
Basename of argument from input source n or the n'th argument without extension. It is a combination of {n}, {/}, and {.}. See -a and -N.

{n/.} can be used the same places as {n}.

::: arguments (alpha testing)
Use arguments from the command line as input source instead of from stdin (standard input). Unlike other options for  parallel ::: is placed after the command and before the arguments.

The following are equivalent:

  (echo file1; echo file2) | parallel gzip
  parallel gzip ::: file1 file2
  parallel gzip {} ::: file1 file2
  parallel --arg-sep ,, gzip {} ,, file1 file2
  parallel --arg-sep ,, gzip ,, file1 file2
  parallel ::: "gzip file1" "gzip file2"

To avoid treating ::: as special use --arg-sep to set the argument separator to something else. See also --arg-sep.

stdin (standard input) will be passed to the first process run.

If multiple ::: are given, each group will be treated as an input source, and all combinations of input sources will be generated. E.g. ::: 1 2 ::: a b c will result in the combinations (1,a) (1,b) (1,c) (2,a) (2,b) (2,c). This is useful for replacing nested for-loops.

::: and :::: can be mixed. So these are equivalent:

  parallel echo {1} {2} {3} ::: 6 7 ::: 4 5 ::: 1 2 3
  parallel echo {1} {2} {3} :::: <(seq 6 7) <(seq 4 5) :::: <(seq 1 3)
  parallel -a <(seq 6 7) echo {1} {2} {3} :::: <(seq 4 5) :::: <(seq 1 3)
  parallel -a <(seq 6 7) -a <(seq 4 5) echo {1} {2} {3} ::: 1 2 3
  seq 6 7 | parallel -a - -a <(seq 4 5) echo {1} {2} {3} ::: 1 2 3
  seq 4 5 | parallel echo {1} {2} {3} :::: <(seq 6 7) - ::: 1 2 3
:::: argfiles (alpha testing)
Another way to write -a argfile1 -a argfile2 ...

::: and :::: can be mixed.

See -a.

--null
-0
Use NUL as delimiter. Normally input lines will end in \n (newline). If they end in \0 (NUL), then use this option. It is useful for processing arguments that may contain \n (newline).
--arg-file input-file
-a input-file
Use input-file as input source. If you use this option, stdin is given to the first process run. Otherwise, stdin is redirected from /dev/null.

If multiple -a are given, each input-file will be treated as an input source, and all combinations of input sources will be generated. E.g. The file foo contains 1 2, the file bar contains a b c. -a foo -a bar will result in the combinations (1,a) (1,b) (1,c) (2,a) (2,b) (2,c). This is useful for replacing nested for-loops.

See also --xapply

--arg-file-sep sep-str
Use sep-str instead of :::: as separator string between command and argument files. Useful if :::: is used for something else by the command.

See also: ::::.

--arg-sep sep-str
Use sep-str instead of ::: as separator string. Useful if ::: is used for something else by the command.

Also useful if you command uses ::: but you still want to read arguments from stdin (standard input): Simply change --arg-sep to a string that is not in the command line.

See also: :::.

--basefile file
-B file
file will be transferred to each sshlogin before a jobs is started. It will be removed if --cleanup is active. The file may be a script to run or some common base data needed for the jobs. Multiple -B can be specified to transfer more basefiles. The file will be transferred the same way as --transfer.
--basenamereplace replace-str
--bnr replace-str
Use the replacement string replace-str instead of {/} for basename of input line.
--basenameextensionreplace replace-str
Use the replacement string replace-str instead of {/.} for basename of input line without extension.
--bg
Run command in background thus  parallel will not wait for completion of the command before exiting. This is the default if --semaphore is set.

See also: --fg

Implies --semaphore.

--block size
--block-size size
Size of block in bytes. The size can be postfixed with K, M, G, or T which would multiply the size with 1024, 1048576, 1073741824, or 1099511627776 respectively.

 parallel tries to meet the block size but can be off by the length of one record.

size defaults to 1M.

See --pipe for use of this.

--cleanup
Remove transferred files. --cleanup will remove the transferred files on the remote computer after processing is done.
  find log -name '*gz' | parallel \
    --sshlogin server.example.com --transfer --return {.}.bz2 \
    --cleanup "zcat {} | bzip -9 >{.}.bz2"

With --transfer the file transferred to the remote computer will be removed on the remote computer. Directories created will not be removed - even if they are empty.

With --return the file transferred from the remote computer will be removed on the remote computer. Directories created will not be removed - even if they are empty.

--cleanup is ignored when not used with --transfer or --return.

--colsep regexp
-C regexp
Column separator. The input will be treated as a table with regexp separating the columns. The n'th column can be access using {n} or {n.}. E.g. {3} is the 3rd column.

--colsep implies --trim rl.

regexp is a Perl Regular Expression: http://perldoc.perl.org/perlre.html

--delimiter delim
-d delim
Input items are terminated by the specified character. Quotes and backslash are not special; every character in the input is taken literally. Disables the end-of-file string, which is treated like any other argument. This can be used when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. The specified delimiter may be a single character, a C-style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported.
--dirnamereplace replace-str (alpha testing)
--dnr replace-str (alpha testing)
Use the replacement string replace-str instead of {//} for dirname of input line.
-E eof-str
Set the end of file string to eof-str. If the end of file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end of file string is used.
--dry-run
Print the job to run on standard output, but do not run the job. Use -v -v to include the ssh/rsync wrapping if the job would be run on a remote computer. Do not count on this literaly, though, as the job may be scheduled on another computer or the local computer if : is in the list.
--eof[=eof-str]
-e[eof-str]
This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant for xargs while this option is not. If eof-str is omitted, there is no end of file string. If neither -E nor -e is used, no end of file string is used.
--eta (beta testing)
Show the estimated number of seconds before finishing. This forces  parallel to read all jobs before starting to find the number of jobs.  parallel normally only reads the next job to run. Implies --progress.
--fg
Run command in foreground thus  parallel will wait for completion of the command before exiting.

See also: --bg

Implies --semaphore.

--
Behave like  parallel. If --tollef and -- are both set, -- takes precedence.
--group
-g
Group output. Output from each jobs is grouped together and is only printed when the command is finished. STDERR first followed by STDOUT. -g is the default. Can be reversed with -u.
--help
-h
Print a summary of the options to  parallel and exit.
--halt-on-error <0|1|2>
-H <0|1|2>
  1. Do not halt if a job fails. Exit status will be the number of jobs failed. This is the default.
  2. Do not start new jobs if a job fails, but complete the running jobs including cleanup. The exit status will be the exit status from the last failing job.
  3. Kill off all jobs immediately and exit without cleanup. The exit status will be the exit status from the failing job.
-I replace-str
Use the replacement string replace-str instead of {}.
--replace[=replace-str]
-i[replace-str]
This option is a synonym for -Ireplace-str if replace-str is specified, and for -I{} otherwise. This option is deprecated; use -I instead.
--joblog logfile
Logfile for executed jobs. Saved a list of the executed jobs to logfile in the following TAB separated format: sequence number, sshlogin, start time as seconds since epoch, run time in seconds, bytes in files transfered, bytes in files returned, exit status, and command run.

To convert the times into ISO-8601 strict do:

perl -a -F"\t" -ne 'chomp($F[2]=`date -d \@$F[2] +%FT%T`); print join("\t",@F)'

--jobs N
-j N
--max-procs N
-P N
Number of jobslots. Run up to N jobs in parallel. 0 means as many as possible. Default is 100% which will run one job per CPU core.

If --semaphore is set default is 1 thus making a mutex.

--jobs +N
-j +N
--max-procs +N
-P +N
Add N to the number of CPU cores. Run this many jobs in parallel. For compute intensive jobs -j +0 is useful as it will run number-of-cpu-cores jobs simultaneously. See also --use-cpus-instead-of-cores.
--jobs -N
-j -N
--max-procs -N
-P -N
Subtract N from the number of CPU cores. Run this many jobs in parallel. If the evaluated number is less than 1 then 1 will be used. See also --use-cpus-instead-of-cores.
--jobs N%
-j N%
--max-procs N%
-P N%
Multiply N% with the number of CPU cores. Run this many jobs in parallel. If the evaluated number is less than 1 then 1 will be used. See also --use-cpus-instead-of-cores.
--jobs procfile
-j procfile
--max-procs procfile
-P procfile
Read parameter from file. Use the content of procfile as parameter for -j. E.g. procfile could contain the string 100% or +2 or 10. If procfile is changed when a job completes, procfile is read again and the new number of jobs is computed. If the number is lower than before, running jobs will be allowed to finish but new jobs will not be started until the wanted number of jobs has been reached. This makes it possible to change the number of simultaneous running jobs while  parallel is running.
--keep-order
-k
Keep sequence of output same as the order of input. Try this to see the difference:
  parallel -j4 sleep {}\; echo {} ::: 2 1 4 3
  parallel -j4 -k sleep {}\; echo {} ::: 2 1 4 3
-L max-lines
Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line.

-L 0 means read one line, but insert 0 arguments on the command line.

Implies -X unless -m is set.

--max-lines[=max-lines]
-l[max-lines]
Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead.

-l 0 is an alias for -l 1.

Implies -X unless -m is set.

--load max-load (alpha testing)
Do not start new jobs on a given computer unless the load is less than max-load. max-load uses the same syntax as --jobs, so 100% for one per CPU is a valid setting.

The load average is only sampled every 10 seconds to avoid stressing small computers.

--controlmaster (experimental)
-M (experimental)
Use ssh's ControlMaster to make ssh connections faster. Useful if jobs run remote and are very fast to run. This is disabled for sshlogins that specify their own ssh command.
--xargs
-m
Multiple. Insert as many arguments as the command line length permits. If {} is not used the arguments will be appended to the line. If {} is used multiple times each {} will be replaced with all the arguments.

Support for -m with --sshlogin is limited and may fail.

See also -X for context replace. If in doubt use -X as that will most likely do what is needed.

--output-as-files
--outputasfiles
--files
Instead of printing the output to stdout (standard output) the output of each job is saved in a file and the filename is then printed.
--pipe
--spreadstdin
Spread input to jobs on stdin. Read a block of data from stdin (standard input) and give one block of data as input to one job.

The block size is determined by --block. The strings --recstart and --recend tell  parallel how a record starts and/or ends. The block read will have the final partial record removed before the block is passed on to the job. The partial record will be prepended to next block.

If --recstart is given this will be used to split at record start.

If --recend is given this will be used to split at record end.

If both --recstart and --recend are given both will have to match to find a split position.

If neither --recstart nor --recend are given --recend defaults to '\n'. To have no record separator use --recend "".

--files is often used with --pipe.

--progress
Show progress of computations. List the computers involved in the task with number of CPU cores detected and the max number of jobs to run. After that show progress for each computer: number of running jobs, number of completed jobs, and percentage of all jobs done by this computer. The percentage will only be available after all jobs have been scheduled as  parallel only read the next job when ready to schedule it - this is to avoid wasting time and memory by reading everything at startup.

By sending  parallel SIGUSR2 you can toggle turning on/off --progress on a running  parallel process.

--max-args=max-args
-n max-args
Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case  parallel will exit.

-n 0 means read one argument, but insert 0 arguments on the command line.

Implies -X unless -m is set.

--max-replace-args=max-args
-N max-args
Use at most max-args arguments per command line. Like -n but also makes replacement strings {1} .. {max-args} that represents argument 1 .. max-args. If too few args the {n} will be empty.

-N 0 means read one argument, but insert 0 arguments on the command line.

This will set the owner of the homedir to the user:

tr ':' '\012' < /etc/passwd | parallel -N7 chown {1} {6}

Implies -X unless -m or <--pipe> is set.

When used with --pipe -N is the number of records to read. This is much slower than --blocksize so avoid it if performance is important.

--max-line-length-allowed
Print the maximal number characters allowed on the command line and exit (used by  parallel itself to determine the line length on remote computers).
--number-of-cpus
Print the number of physical CPUs and exit (used by  parallel itself to determine the number of physical CPUs on remote computers).
--number-of-cores
Print the number of CPU cores and exit (used by  parallel itself to determine the number of CPU cores on remote computers).
--nice niceness
Run the command at this niceness. For simple commands you can just add nice in front of the command. But if the command consists of more sub commands (Like: ls|wc) then prepending nice will not always work. --nice will make sure all sub commands are niced.
--interactive
-p
Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with 'y' or 'Y'. Implies -t.
--profile profilename
-J profilename
Use profile profilename for options. This is useful if you want to have multiple profiles. You could have one profile for running jobs in parallel on the local computer and a different profile for running jobs on remote computers. See the section PROFILE FILES for examples.

profilename corresponds to the file ~/.parallel/profilename.

Default: config

--quote
-q
Quote command. This will quote the command line so special characters are not interpreted by the shell. See the section QUOTING. Most people will never need this. Quoting is disabled by default.
--no-run-if-empty
-r
If the stdin (standard input) only contains whitespace, do not run the command.
--recstart startstring
--recend endstring
If --recstart is given startstring will be used to split at record start.

If --recend is given endstring will be used to split at record end.

If both --recstart and --recend are given the string startstringendstring will have to match to find a split position. This is useful if either startstring or endstring match in the middle of a record.

If neither --recstart nor --recend are given then --recend defaults to '\n'. To have no record separator use --recend "".

--recstart and --recend are used with --pipe.

Use --regexp to interpret --recstart and --recend as regular expressions. This is slow, however.

--regexp (beta testing)
Use --regexp to interpret --recstart and --recend as regular expressions. This is slow, however.
--remove-rec-sep
--removerecsep
--rrs
Remove the text matched by --recstart and --recend before piping it to the command.

Only used with --pipe.

--retries n
If a job fails, retry it on another computer. Do this n times. If there are fewer than n computers in --sshlogin  parallel will re-use the computers. This is useful if some jobs fail for no apparent reason (such as network failure).
--return filename
Transfer files from remote computers. --return is used with --sshlogin when the arguments are files on the remote computers. When processing is done the file filename will be transferred from the remote computer using rsync and will be put relative to the default login dir. E.g.
  echo foo/bar.txt | parallel \
    --sshlogin server.example.com --return {.}.out touch {.}.out

This will transfer the file $HOME/foo/bar.out from the computer server.example.com to the file foo/bar.out after running touch foo/bar.out on server.example.com.

  echo /tmp/foo/bar.txt | parallel \
    --sshlogin server.example.com --return {.}.out touch {.}.out

This will transfer the file /tmp/foo/bar.out from the computer server.example.com to the file /tmp/foo/bar.out after running touch /tmp/foo/bar.out on server.example.com.

Multiple files can be transferred by repeating the options multiple times:

  echo /tmp/foo/bar.txt | \
    parallel --sshlogin server.example.com \
    --return {.}.out --return {.}.out2 touch {.}.out {.}.out2

--return is often used with --transfer and --cleanup.

--return is ignored when used with --sshlogin : or when not used with --sshlogin.

--max-chars=max-chars
-s max-chars
Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment. The default value is the maximum.

Implies -X unless -m is set.

--show-limits
Display the limits on the command-line length which are imposed by the operating system and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want  parallel to do anything.
--semaphore
Work as a counting semaphore. --semaphore will cause  parallel to start command in the background. When the number of simultaneous jobs is reached,  parallel will wait for one of these to complete before starting another command.

--semaphore implies --bg unless --fg is specified.

--semaphore implies --semaphorename `tty` unless --semaphorename is specified.

Used with --fg, --wait, and --semaphorename.

The command sem is an alias for parallel --semaphore.

--semaphorename name
--id name
The name of the semaphore to use. The semaphore can be shared between multiple processes.

Implies --semaphore.

--semaphoretimeout secs (not implemented)
If the semaphore is not released within secs seconds, take it anyway.

Implies --semaphore.

--seqreplace replace-str
Use the replacement string replace-str instead of {#} for job sequence number.
--skip-first-line
Do not use the first line of input (used by  parallel itself when called with --shebang).
-S [ncpu/]sshlogin[,[ncpu/]sshlogin[,...]]
--sshlogin [ncpu/]sshlogin[,[ncpu/]sshlogin[,...]]
Distribute jobs to remote computers. The jobs will be run on a list of remote computers.  parallel will determine the number of CPU cores on the remote computers and run the number of jobs as specified by -j. If the number ncpu is given  parallel will use this number for number of CPU cores on the host. Normally ncpu will not be needed.

An sshlogin is of the form:

  [sshcommand [options]][username@]hostname

The sshlogin must not require a password.

The sshlogin ':' is special, it means 'no ssh' and will therefore run on the local computer.

The sshlogin '..' is special, it read sshlogins from ~/.parallel/sshloginfile

To specify more sshlogins separate the sshlogins by comma or repeat the options multiple times.

For examples: see --sshloginfile.

The remote host must have  parallel installed.

--sshlogin is known to cause problems with -m and -X.

--sshlogin is often used with --transfer, --return, --cleanup, and --trc.

--sshloginfile filename
File with sshlogins. The file consists of sshlogins on separate lines. Empty lines and lines starting with '#' are ignored. Example:
  server.example.com
  [email protected]
  8/my-8-core-server.example.com
  2/[email protected]
  # This server has SSH running on port 2222
  ssh -p 2222 server.example.net
  4/ssh -p 2222 quadserver.example.net
  # Use a different ssh program
  myssh -p 2222 -l myusername hexacpu.example.net
  # Use a different ssh program with default number of cores
  //usr/local/bin/myssh -p 2222 -l myusername hexacpu.example.net
  # Use a different ssh program with 6 cores
  6//usr/local/bin/myssh -p 2222 -l myusername hexacpu.example.net
  # Assume 16 cores on the local computer
  16/:

When using a different ssh program the last argument must be the hostname.

The sshloginfile '..' is special, it read sshlogins from ~/.parallel/sshloginfile

--silent
Silent. The job to be run will not be printed. This is the default. Can be reversed with -v.
--tty
-T
Open terminal tty. If  parallel is used for starting an interactive program then this option may be needed. It will start only one job at a time (i.e. -j1), not buffer the output (i.e. -u), and it will open a tty for the job. When the job is done, the next job will get the tty.
--tmpdir dirname
Directory for temporary files.  parallel normally buffers output into temporary files in /tmp. By setting --tmpdir you can use a different dir for the files. Setting --tmpdir is equivalent to setting $TMPDIR.
--tollef
Make  parallel behave like Tollef's parallel command. To override use --.
--verbose
-t
Print the job to be run on standard error.

See also -v and -p.

--transfer
Transfer files to remote computers. --transfer is used with --sshlogin when the arguments are files and should be transferred to the remote computers. The files will be transferred using rsync and will be put relative to the default login dir. E.g.
  echo foo/bar.txt | parallel \
    --sshlogin server.example.com --transfer wc

This will transfer the file foo/bar.txt to the computer server.example.com to the file $HOME/foo/bar.txt before running wc foo/bar.txt on server.example.com.

  echo /tmp/foo/bar.txt | parallel \
    --sshlogin server.example.com --transfer wc

This will transfer the file foo/bar.txt to the computer server.example.com to the file /tmp/foo/bar.txt before running wc /tmp/foo/bar.txt on server.example.com.

--transfer is often used with --return and --cleanup.

--transfer is ignored when used with --sshlogin : or when not used with --sshlogin.

--trc filename
Transfer, Return, Cleanup. Short hand for:

--transfer --return filename --cleanup

--trim <n|l|r|lr|rl>
Trim white space in input.
n
No trim. Input is not modified. This is the default.
l
Left trim. Remove white space from start of input. E.g. " a bc " -> "a bc ".
r
Right trim. Remove white space from end of input. E.g. " a bc " -> " a bc".
lr
rl
Both trim. Remove white space from both start and end of input. E.g. " a bc " -> "a bc". This is the default if --colsep is used.
--ungroup
-u
Ungroup output. Output is printed as soon as possible. This may cause output from different commands to be mixed.  parallel runs faster with -u. Can be reversed with -g.
--extensionreplace replace-str
-U replace-str
Use the replacement string replace-str instead of {.} for input line without extension.
--use-cpus-instead-of-cores
Count the number of physical CPUs instead of CPU cores. When computing how many jobs to run simultaneously relative to the number of CPU cores you can ask  parallel to instead look at the number of physical CPUs. This will make sense for computers that have hyperthreading as two jobs running on one CPU with hyperthreading will run slower than two jobs running on two physical CPUs. Some multi-core CPUs can run faster if only one thread is running per physical CPU. Most users will not need this option.
-v
Verbose. Print the job to be run on standard output. Can be reversed with --silent. See also -t.

Use -v -v to print the wrapping ssh command when running remotely.

--version
-V
Print the version  parallel and exit.
--workdir mydir
-W mydir
Files transferred using --transfer and --return will be relative to mydir on remote computers, and the command will be executed in that dir. The special workdir ... will create a workdir in ~/.parallel/tmp/ on the remote computers and will be removed if using --cleanup.
--wait
Wait for all commands to complete.

Implies --semaphore.

-X
Multiple arguments with context replace. Insert as many arguments as the command line length permits. If {} is not used the arguments will be appended to the line. If {} is used as part of a word (like pic{}.jpg) then the whole word will be repeated. If {} is used multiple times each {} will be replaced with the arguments.

Normally -X will do the right thing, whereas -m can give unexpected results if {} is used as part of a word.

Support for -X with --sshlogin is limited and may fail.

See also -m.

--exit
-x
Exit if the size (see the -s option) is exceeded.
--xapply (alpha testing)
Read multiple files like xapply. If multiple -a are given, one line will be read from each of the files. The arguments can be accessed in the command as {1} .. {n}, so {1} will be a line from the first file, and {6} will refer to the line with the same line number from the 6th file.

Compare these two:

  parallel echo {1} {2} ::: 1 2 3 ::: a b c
  parallel --xapply echo {1} {2} ::: 1 2 3 ::: a b c
--shebang
--hashbang
-Y
 Parallel can be called as a shebang (#!) command as the first line of a script. Like this:
  #!/usr/bin/parallel -Yr traceroute
  foss.org.my
  debian.org
  freenetproject.org

For this to work --shebang or -Y must be set as the first option.

Examples

EXAMPLE: Working as xargs -n1. Argument appending

parallel can work similar to xargs -n1.

To compress all html files using gzip run:

find . -name '*.html' | parallel gzip

If the file names may contain a newline use -0. Substitute FOO BAR with FUBAR in all files in this dir and subdirs:

find . -type f -print0 | parallel -q0 perl -i -pe 's/FOO BAR/FUBAR/g'

Note -q is needed because of the space in 'FOO BAR'.

parallel can take the arguments from command line instead of stdin (standard input). To compress all html files in the current dir using gzip run:

parallel gzip ::: *.html

To convert *.wav to *.mp3 using LAME running one process per CPU core run:

parallel lame {} -o {.}.mp3 ::: *.wav

EXAMPLE: Inserting multiple arguments

When moving a lot of files like this: mv * destdir you will sometimes get the error:

bash: /bin/mv: Argument list too long

because there are too many files. You can instead do:

ls | parallel mv {} destdir

This will run mv for each file. It can be done faster if mv gets as many arguments that will fit on the line:

ls | parallel -m mv {} destdir

EXAMPLE: Context replace

To remove the files pict0000.jpg .. pict9999.jpg you could do:

seq -w 0 9999 | parallel rm pict{}.jpg

You could also do:

seq -w 0 9999 | perl -pe 's/(.*)/pict$1.jpg/' | parallel -m rm

The first will run rm 10000 times, while the last will only run rm as many times needed to keep the command line length short enough to avoid Argument list too long (it typically runs 1-2 times).

You could also run:

seq -w 0 9999 | parallel -X rm pict{}.jpg

This will also only run rm as many times needed to keep the command line length short enough.

EXAMPLE: Compute intensive jobs and substitution

If ImageMagick is installed this will generate a thumbnail of a jpg file:

convert -geometry 120 foo.jpg thumb_foo.jpg

This will run with number-of-cpu-cores jobs in parallel for all jpg files in a directory:

ls *.jpg | parallel convert -geometry 120 {} thumb_{}

To do it recursively use find:

find . -name '*.jpg' | parallel convert -geometry 120 {} {}_thumb.jpg

Notice how the argument has to start with {} as {} will include path (e.g. running convert -geometry 120 ./foo/bar.jpg thumb_./foo/bar.jpg would clearly be wrong). The command will generate files like ./foo/bar.jpg_thumb.jpg.

Use {.} to avoid the extra .jpg in the file name. This command will make files like ./foo/bar_thumb.jpg:

find . -name '*.jpg' | parallel convert -geometry 120 {} {.}_thumb.jpg

EXAMPLE: Substitution and redirection

This will generate an uncompressed version of .gz-files next to the .gz-file:

parallel zcat {} ">"{.} ::: *.gz

Quoting of > is necessary to postpone the redirection. Another solution is to quote the whole command:

parallel "zcat {} >{.}" ::: *.gz

Other special shell charaters (such as * ; $ > < | >> <<) also need to be put in quotes, as they may otherwise be interpreted by the shell and not given to parallel.

EXAMPLE: Composed commands

A job can consist of several commands. This will print the number of files in each directory:

ls | parallel 'echo -n {}" "; ls {}|wc -l'

To put the output in a file called <name>.dir:

ls | parallel '(echo -n {}" "; ls {}|wc -l) > {}.dir'

Even small shell scripts can be run by parallel:

find . | parallel 'a={}; name=${a##*/}; upper=$(echo "$name" | tr "[:lower:]" "[:upper:]"); echo "$name - $upper"'

ls | parallel 'mv {} "$(echo {} | tr "[:upper:]" "[:lower:]")"'

Given a list of URLs, list all URLs that fail to download. Print the line number and the URL.

cat urlfile | parallel "wget {} 2>/dev/null || grep -n {} urlfile"

Create a mirror directory with the same filenames except all files and symlinks are empty files.

cp -rs /the/source/dir mirror_dir; find mirror_dir -type l | parallel -m rm {} '&&' touch {}

EXAMPLE: Removing file extension when processing files

When processing files removing the file extension using {.} is often useful.

Create a directory for each zip-file and unzip it in that dir:

parallel 'mkdir {.}; cd {.}; unzip ../{}' ::: *.zip

Recompress all .gz files in current directory using bzip2 running 1 job per CPU core in parallel:

parallel "zcat {} | bzip2 >{.}.bz2 && rm {}" ::: *.gz

Convert all WAV files to MP3 using LAME:

find sounddir -type f -name '*.wav' | parallel lame {} -o {.}.mp3

Put all converted in the same directory:

find sounddir -type f -name '*.wav' | parallel lame {} -o mydir/{/.}.mp3

EXAMPLE: Removing two file extensions when processing files and calling Parallel from itself

If you have directory with tar.gz files and want these extracted in the corresponding dir (e.g foo.tar.gz will be extracted in the dir foo) you can do:

ls *.tar.gz| parallel -U {tar} 'echo {tar}|parallel "mkdir -p {.} ; tar -C {.} -xf {.}.tar.gz"'

EXAMPLE: Download 10 images for each of the past 30 days

Let us assume a website stores images like:

     http://www.example.com/path/to/YYYYMMDD_##.jpg

where YYYYMMDD is the date and ## is the number 01-10. This will generate the past 30 days as YYYYMMDD:

seq 30 | parallel date -d '"today -{} days"' +%Y%m%d

Based on this we can let parallel generate 10 wgets per day:

the above | parallel -I {o} seq -w 10 "|" parallel wget http://www.example.com/path/to/{o}_{}.jpg

EXAMPLE: Process files from a tar file while unpacking

If the files to be processed are in a tar file then unpacking one file and processing it immediately may be faster than first unpacking all files.

tar xvf foo.tgz | perl -ne 'print $l;$l=$_;END{print $l}' | parallel echo

The Perl one-liner is needed to avoid race condition.

EXAMPLE: Rewriting a for-loop and a while-read-loop

for-loops like this:

  (for x in `cat list` ; do
    do_something $x
  done) | process_output

and while-read-loops like this:

  cat list | (while read x ; do
    do_something $x
  done) | process_output

can be written like this:

cat list | parallel do_something | process_output

If the processing requires more steps the for-loop like this:

 (for x in `cat list` ; do
   no_extension=${x%.*};
   do_something $x scale $no_extension.jpg
   do_step2 <$x $no_extension
 done) | process_output

and while-loops like this:

 cat list | (while read x ; do
   no_extension=${x%.*};
   do_something $x scale $no_extension.jpg
   do_step2 <$x $no_extension
 done) | process_output

can be written like this:

cat list | parallel "do_something {} scale {.}.jpg ; do_step2 <{} {.}" | process_output

EXAMPLE: Rewriting nested for-loops

Nested for-loops like this:

  (for x in `cat xlist` ; do
    for y in `cat ylist` ; do
      do_something $x $y
    done
  done) | process_output

can be written like this:

cat xlist | parallel cat ylist \| parallel -I {o} do_something {} {o} | process_output

The above will run N*N jobs in parallel if parallel normally runs N jobs. To ensure the output order is the same as the input and only run N jobs do:

cat xlist | parallel -k cat ylist \| parallel -j1 -kI {o} do_something {} {o} | process_output

EXAMPLE: Group output lines

When running jobs that output data, you often do not want the output of multiple jobs to run together. parallel defaults to grouping the output of each job, so the output is printed when the job finishes. If you want the output to be printed while the job is running you can use -u.

Compare the output of:

parallel traceroute ::: foss.org.my debian.org freenetproject.org

to the output of:

parallel -u traceroute ::: foss.org.my debian.org freenetproject.org

EXAMPLE: Keep order of output same as order of input

Normally the output of a job will be printed as soon as it completes. Sometimes you want the order of the output to remain the same as the order of the input. This is often important, if the output is used as input for another system. -k will make sure the order of output will be in the same order as input even if later jobs end before earlier jobs.

Append a string to every line in a text file:

cat textfile | parallel -k echo {} append_string

If you remove -k some of the lines may come out in the wrong order.

Another example is traceroute:

parallel traceroute ::: foss.org.my debian.org freenetproject.org

will give traceroute of foss.org.my, debian.org and freenetproject.org, but it will be sorted according to which job completed first.

To keep the order the same as input run:

parallel -k traceroute ::: foss.org.my debian.org freenetproject.org

This will make sure the traceroute to foss.org.my will be printed first.

A bit more complex example is downloading a huge file in chunks in parallel: Some internet connections will deliver more data if you download files in parallel. For downloading files in parallel see: "EXAMPLE: Download 10 images for each of the past 30 days". But if you are downloading a big file you can download the file in chunks in parallel.

To download byte 10000000-19999999 you can use curl:

curl -r 10000000-19999999 http://example.com/the/big/file > file.part

To download a 1 GB file we need 100 10MB chunks downloaded and combined in the correct order.

seq 0 99 | parallel -k curl -r \ {}0000000-{}9999999 http://example.com/the/big/file > file

EXAMPLE: Parallel grep

grep -r greps recursively through directories. On multicore CPUs parallel can often speed this up.

find . -type f | parallel -k -j150% -n 1000 -m grep -H -n STRING {}

This will run 1.5 job per core, and give 1000 arguments to grep.

To grep a big file in parallel use --pipe:

cat bigfile | parallel --pipe grep foo

Depending on your disks and CPUs it may be faster to read larger blocks:

cat bigfile | parallel --pipe --block 10M grep foo

EXAMPLE: Using remote computers

To run commands on a remote computer SSH needs to be set up and you must be able to login without entering a password (The commands ssh-copy-id and ssh-agent may help you do that).

To run echo on server.example.com:

  seq 10 | parallel --sshlogin server.example.com echo

To run commands on more than one remote computer run:

  seq 10 | parallel --sshlogin server.example.com,server2.example.net echo

Or:

  seq 10 | parallel --sshlogin server.example.com \
    --sshlogin server2.example.net echo

If the login username is foo on server2.example.net use:

  seq 10 | parallel --sshlogin server.example.com \
    --sshlogin [email protected] echo

To distribute the commands to a list of computers, make a file mycomputers with all the computers:

  server.example.com
  [email protected]
  server3.example.com

Then run:

  seq 10 | parallel --sshloginfile mycomputers echo

To include the local computer add the special sshlogin ':' to the list:

  server.example.com
  [email protected]
  server3.example.com
  :

parallel will try to determine the number of CPU cores on each of the remote computers, and run one job per CPU core - even if the remote computers do not have the same number of CPU cores.

If the number of CPU cores on the remote computers is not identified correctly the number of CPU cores can be added in front. Here the computer has 8 CPU cores.

  seq 10 | parallel --sshlogin 8/server.example.com echo

EXAMPLE: Transferring of files

To recompress gzipped files with bzip2 using a remote computer run:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com \
    --transfer "zcat {} | bzip2 -9 >{.}.bz2"

This will list the .gz-files in the logs directory and all directories below. Then it will transfer the files to server.example.com to the corresponding directory in $HOME/logs. On server.example.com the file will be recompressed using zcat and bzip2 resulting in the corresponding file with .gz replaced with .bz2.

If you want the resulting bz2-file to be transferred back to the local computer add --return {.}.bz2:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com \
    --transfer --return {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"

After the recompressing is done the .bz2-file is transferred back to the local computer and put next to the original .gz-file.

If you want to delete the transferred files on the remote computer add --cleanup. This will remove both the file transferred to the remote computer and the files transferred from the remote computer:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com \
    --transfer --return {.}.bz2 --cleanup "zcat {} | bzip2 -9 >{.}.bz2"

If you want run on several computers add the computers to --sshlogin either using ',' or multiple --sshlogin:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com,server2.example.com \
    --sshlogin server3.example.com \
    --transfer --return {.}.bz2 --cleanup "zcat {} | bzip2 -9 >{.}.bz2"

You can add the local computer using --sshlogin :. This will disable the removing and transferring for the local computer only:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com,server2.example.com \
    --sshlogin server3.example.com \
    --sshlogin : \
    --transfer --return {.}.bz2 --cleanup "zcat {} | bzip2 -9 >{.}.bz2"

Often --transfer, --return and --cleanup are used together. They can be shortened to --trc:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com,server2.example.com \
    --sshlogin server3.example.com \
    --sshlogin : \
    --trc {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"

With the file mycomputers containing the list of computers it becomes:

  find logs/ -name '*.gz' | parallel --sshloginfile mycomputers \
    --trc {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"

If the file ~/.parallel/sshloginfile contains the list of computers the special short hand -S .. can be used:

  find logs/ -name '*.gz' | parallel -S .. \
    --trc {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"

EXAMPLE: Distributing work to local and remote computers

Convert *.mp3 to *.ogg running one process per CPU core on local computer and server2:

  parallel --trc {.}.ogg -S server2,: \
  'mpg321 -w - {} | oggenc -q0 - -o {.}.ogg' ::: *.mp3

EXAMPLE: Use multiple inputs in one command

Copy files like foo.es.ext to foo.ext:

ls *.es.* | perl -pe 'print; s/\.es//' | parallel -N2 cp {1} {2}

The perl command spits out 2 lines for each input. parallel takes 2 inputs (using -N2) and replaces {1} and {2} with the inputs.

Print the number on the opposing sides of a six sided die:

parallel -a <(seq 6) -a <(seq 6 -1 1) echo

parallel echo :::: <(seq 6) <(seq 6 -1 1)

Convert files from all subdirs to PNG-files with consecutive numbers (useful for making input PNG's for ffmpeg):

parallel -a <(find . -type f | sort) -a <(seq $(find . -type f|wc -l)) convert {1} {2}.png

Alternative version:

find . -type f | sort | parallel convert {} \$PARALLEL_SEQ.png

EXAMPLE: Use a table as input

Content of table_file.tsv:

  foo<TAB>bar
  baz <TAB> quux

To run:

  cmd -o bar -i foo
  cmd -o quux -i baz

you can run:

parallel -a table_file.tsv --colsep '\t' cmd -o {2} -i {1}

Note: The default for parallel is to remove the spaces around the columns. To keep the spaces:

parallel -a table_file.tsv --trim n --colsep '\t' cmd -o {2} -i {1}

EXAMPLE: Run the same command 10 times

If you want to run the same command with the same arguments 10 times in parallel you can do:

seq 10 | parallel -n0 my_command my_args

EXAMPLE: Working as cat | sh. Resource inexpensive jobs and evaluation

parallel can work similar to cat | sh.

A resource inexpensive job is a job that takes very little CPU, disk I/O and network I/O. Ping is an example of a resource inexpensive job. wget is too - if the webpages are small.

The content of the file jobs_to_run:

  ping -c 1 10.0.0.1
  wget http://example.com/status.cgi?ip=10.0.0.1
  ping -c 1 10.0.0.2
  wget http://example.com/status.cgi?ip=10.0.0.2
  ...
  ping -c 1 10.0.0.255
  wget http://example.com/status.cgi?ip=10.0.0.255

To run 100 processes simultaneously do:

parallel -j 100 < jobs_to_run

As there is not a command the jobs will be evaluated by the shell.

EXAMPLE: Processing a big file using more cores

To process a big file or some output you can use --pipe to split up the data into blocks and pipe the blocks into the processing program.

If the program is gzip -9 you can do:

cat bigfile | parallel --pipe --recend '' -k gzip -9 >bigfile.gz

This will split bigfile into blocks of 1 MB and pass that to gzip -9 in parallel. One gzip will be run per CPU core. The output of gzip -9 will be kept in order and saved to bigfile.gz

gzip works fine if the output is appended, but some processing does not work like that - for example sorting. For this parallel can put the output of each command into a file. This will sort a big file in parallel:

cat bigfile | parallel --pipe --files sort | parallel -Xj1 sort -m {} ';' rm {} >bigfile.sort

Here bigfile is split into blocks of around 1MB, each block ending in '\n' (which is the default for --recend). Each block is passed to sort and the output from sort is saved into files. These files are passed to the second parallel that runs sort -m on the files before it removes the files. The output is saved to bigfile.sort.

EXAMPLE: Working as mutex and counting semaphore

The command sem is an alias for parallel --semaphore.

A counting semaphore will allow a given number of jobs to be started in the background. When the number of jobs are running in the background, sem will wait for one of these to complete before starting another command. sem --wait will wait for all jobs to complete.

Run 10 jobs concurrently in the background:

  for i in `ls *.log` ; do
    echo $i
    sem -j10 gzip $i ";" echo done
  done
  sem --wait

A mutex is a counting semaphore allowing only one job to run. This will edit the file myfile and prepends the file with lines with the numbers 1 to 3.

  seq 3 | parallel sem sed -i -e 'i{}' myfile

As myfile can be very big it is important only one process edits the file at the same time.

Name the semaphore to have multiple different semaphores active at the same time:

  seq 3 | parallel sem --id mymutex sed -i -e 'i{}' myfile

EXAMPLE: Start editor with filenames from stdin (standard input)

You can use Parallel to start interactive programs like emacs or vi:

cat filelist | parallel -T -X emacs

cat filelist | parallel -T -X vi

If there are more files than will fit on a single command line, the editor will be started again with the remaining files.

EXAMPLE: Running sudo

sudo requires a password to run a command as root. It caches the access, so you only need to enter the password again if you have not used sudo for a while.

The command:

  parallel sudo echo ::: This is a bad idea

is no good, as you would be prompted for the sudo password for each of the jobs. You can either do:

  sudo echo This
  parallel sudo echo ::: is a good idea

or:

  sudo parallel echo ::: This is a good idea

This way you only have to enter the sudo password once.

EXAMPLE: Parallel as queue system/batch manager

parallel can work as a simple job queue system or batch manager. The idea is to put the jobs into a file and have parallel read from that continuously. As parallel will stop at end of file we use tail to continue reading:

echo >jobqueue; tail -f jobqueue | parallel

To submit your jobs to the queue:

echo my_command my_arg >> jobqueue

You can of course use -S to distribute the jobs to remote computers:

echo >jobqueue; tail -f jobqueue | parallel -S ..

There are a two small issues when using parallel as queue system/batch manager:

EXAMPLE: Parallel as dir processor

If you have a dir in which users drop files that needs to be processed you can do this on /Linux (If you know what inotifywait is called on other platforms file a bug report):

inotifywait -q -m -r -e CLOSE_WRITE --format %w%f my_dir | parallel -u echo

This will run the command echo on each file put into my_dir or subdirs of my_dir.

The -u is needed because of a small bug in parallel. If that proves to be a problem, file a bug report.

You can of course use -S to distribute the jobs to remote computers:

inotifywait -q -m -r -e CLOSE_WRITE --format %w%f my_dir | parallel -S .. -u echo

If the files to be processed are in a tar file then unpacking one file and processing it immediately may be faster than first unpacking all files. Set up the dir processor as above and unpack into the dir.

QUOTING

parallel is very liberal in quoting. You only need to quote characters that have special meaning in shell:

( ) $ ` ' " < > ; | \

and depending on context these needs to be quoted, too:

* ~ & # ! ? space * {

Therefore most people will never need more quoting than putting '\' in front of the special characters.

However, when you want to use a shell variable you need to quote the $-sign. Here is an example using $PARALLEL_SEQ. This variable is set by parallel itself, so the evaluation of the $ must be done by the sub shell started by parallel:

seq 10 | parallel -N2 echo seq:\$PARALLEL_SEQ arg1:{1} arg2:{2}

If the variable is set before parallel starts you can do this:

VAR=this_is_set_before_starting

echo test | parallel echo {} $VAR

Prints: test this_is_set_before_starting

It is a little more tricky if the variable contains more than one space in a row:

VAR="two spaces between each word"

echo test | parallel echo {} \'"$VAR"\'

Prints: test two spaces between each word

If the variable should not be evaluated by the shell starting parallel but be evaluated by the sub shell started by parallel, then you need to quote it:

echo test | parallel VAR=this_is_set_after_starting \; echo {} \$VAR

Prints: test this_is_set_after_starting

It is a little more tricky if the variable contains space:

echo test | parallel VAR='"two spaces between each word"' echo {} \'"$VAR"\'

Prints: test two spaces between each word

$$ is the shell variable containing the process id of the shell. This will print the process id of the shell running parallel:

seq 10 | parallel echo $$

And this will print the process ids of the sub shells started by parallel.

seq 10 | parallel echo \$\$

If the special characters should not be evaluated by the sub shell then you need to protect it against evaluation from both the shell starting parallel and the sub shell:

echo test | parallel echo {} \\\$VAR

Prints: test $VAR

parallel can protect against evaluation by the sub shell by using -q:

echo test | parallel -q echo {} \$VAR

Prints: test $VAR

This is particularly useful if you have lots of quoting. If you want to run a perl script like this:

perl -ne '/^\S+\s+\S+$/ and print $ARGV,"\n"' file

It needs to be quoted like this:

ls | parallel perl -ne '/^\\S+\\s+\\S+\$/\ and\ print\ \$ARGV,\"\\n\"'

Notice how spaces, \'s, "'s, and $'s need to be quoted. parallel can do the quoting by using option -q:

ls | parallel -q perl -ne '/^\S+\s+\S+$/ and print $ARGV,"\n"'

However, this means you cannot make the sub shell interpret special characters. For example because of -q this WILL NOT WORK:

ls *.gz | parallel -q "zcat {} >{.}"

ls *.gz | parallel -q "zcat {} | bzip2 >{.}.bz2"

because > and | need to be interpreted by the sub shell.

If you get errors like:

  sh: -c: line 0: syntax error near unexpected token
  sh: Syntax error: Unterminated quoted string
  sh: -c: line 0: unexpected EOF while looking for matching `''
  sh: -c: line 1: syntax error: unexpected end of file

then you might try using -q.

If you are using bash process substitution like <(cat foo) then you may try -q and prepending command with bash -c:

ls | parallel -q bash -c 'wc -c <(echo {})'

Or for substituting output:

ls | parallel -q bash -c 'tar c {} | tee >(gzip >{}.tar.gz) | bzip2 >{}.tar.bz2'

Conclusion: To avoid dealing with the quoting problems it may be easier just to write a small script and have parallel call that script.

LIST RUNNING JOBS

If you want a list of the jobs currently running you can run:

killall -USR1 parallel

parallel will then print the currently running jobs on STDERR.

COMPLETE RUNNING JOBS BUT DO NOT START NEW JOBS

If you regret starting a lot of jobs you can simply break parallel, but if you want to make sure you do not have halfcompleted jobs you should send the signal SIGTERM to parallel:

killall -TERM parallel

This will tell parallel to not start any new jobs, but wait until the currently running jobs are finished before exiting.

ENVIRONMENT VARIABLES

$PARALLEL_PID
The environment variable $PARALLEL_PID is set by parallel and is visible to the jobs started from parallel. This makes it possible for the jobs to communicate directly to parallel. Remember to quote the $, so it gets evaluated by the correct shell.

Example: If each of the jobs tests a solution and one of jobs finds the solution the job can tell parallel not to start more jobs by: kill -TERM $PARALLEL_PID. This only works on the local computer.

$PARALLEL_SEQ
$PARALLEL_SEQ will be set to the sequence number of the job running. Remember to quote the $, so it gets evaluated by the correct shell.

Example:

seq 10 | parallel -N2 echo seq:'$'PARALLEL_SEQ arg1:{1} arg2:{2}

$TMPDIR
Directory for temporary files. See: --tmpdir.
$PARALLEL
The environment variable $PARALLEL will be used as default options for parallel. If the variable contains special shell characters (e.g. $, *, or space) then these need to be to be escaped with \.

Example:

cat list | parallel -j1 -k -v ls

can be written as:

cat list | PARALLEL="-kvj1" parallel ls

cat list | parallel -j1 -k -v -S"myssh user@server" ls

can be written as:

cat list | PARALLEL='-kvj1 -S myssh\ user@server' parallel echo

Notice the \ in the middle is needed because 'myssh' and 'user@server' must be one argument.

DEFAULT PROFILE (CONFIG FILE)

The file ~/.parallel/config (formerly known as .parallelrc) will be read if it exists. Lines starting with '#' will be ignored. It can be formatted like the environment variable $PARALLEL, but it is often easier to simply put each option on its own line.

Options on the command line takes precedence over the environment variable $PARALLEL which takes precedence over the file ~/.parallel/config.

PROFILE FILES

If --profile set, parallel will read the profile from that file instead of ~/.parallel/config.

Example: Profile for running every command with -j-1 and nice

  echo -j-1 nice > ~/.parallel/nice_profile
  parallel -J nice_profile bzip2 -9 ::: *

Example: Profile for running a perl script before every command:

  echo "perl -e '\$a=\$\$; print \$a,\" \",'\$PARALLEL_SEQ',\" \";';" > ~/.parallel/pre_perl
  parallel -J pre_perl echo ::: *

Note how the $ and " need to be quoted using \.

Example: Profile for running distributed jobs with nice on the remote computers:

  echo -S .. nice > ~/.parallel/dist
  parallel -J dist --trc {.}.bz2 bzip2 -9 ::: *

EXIT STATUS

If --halt-on-error 0 or not specified:

  1. All jobs ran without error.
  2. -253

    Some of the jobs failed. The exit status gives the number of failed jobs

  3. More than 253 jobs failed.
  4. Other error.

If --halt-on-error 1 or 2: Exit status of the failing job.


BUGS

Quoting of newline

Because of the way newline is quoted this will not work:

echo 1,2,3 | parallel -vkd, "echo 'a{}b'"

However, these will all work:

echo 1,2,3 | parallel -vkd, echo a{}b

echo 1,2,3 | parallel -vkd, "echo 'a'{}'b'"

echo 1,2,3 | parallel -vkd, "echo 'a'"{}"'b'"

Startup speed

parallel is slow at starting up. Half of the startup time on the local computer is spent finding the maximal length of a command line. Setting -s will remove this part of the startup time.

When using multiple computers parallel opens ssh connections to them to figure out how many connections can be used reliably simultaneously (Namely SSHD's MaxStartup). This test is done for each host in serial, so if your --sshloginfile contains many hosts it may be slow.

--nice limits command length

The current implementation of --nice is too pessimistic in the max allowed command length. It only uses a little more than half of what it could. This affects -X and -m. If this becomes a real problem for you file a bug-report.

Aliases and functions do not work

If you get:

Can't exec "command": No such file or directory

or:

open3: exec of by command failed

it may be because command is not known, but it could also be because command is an alias or a function. parallel will never support running aliases and functions (see why http://www.perlmonks.org/index.pl?node_id=484296), so change your alias or function to a script.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Nov 08, 2018] pexec utility is similar to parallel

Nov 08, 2018 | www.gnu.org

Welcome to the web page of the pexec program!

The main purpose of the program pexec is to execute the given command or shell script (e.g. parsed by /bin/sh ) in parallel on the local host or on remote hosts, while some of the execution parameters, namely the redirected standard input, output or error and environmental variables can be varied. This program is therefore capable to replace the classic shell loop iterators (e.g. for ~ in ~ done , in bash ) by executing the body of the loop in parallel. Thus, the program pexec implements shell level data parallelism in a barely simple form. The capabilities of the program is extended with additional features, such as allowing to define mutual exclusions, do atomic command executions and implement higher level resource and job control. See the complete manual for more details. See a brief Hungarian description of the program here .

The actual version of the program package is 1.0rc8 .

You may browse the package directory here (for FTP access, see this directory ). See the GNU summary page of this project here . The latest version of the program source package is pexec-1.0rc8.tar.gz . Here is another mirror of the package directory.

Please consider making donations to the author (via PayPal ) in order to help further development of the program or support the GNU project via the FSF .

[Jun 24, 2018] Three Ways to Script Processes in Parallel by Rudis Muiznieks

Sep 02, 2015 | www.codeword.xyz
Wednesday, September 02, 2015 | 9 Comments

I was recently troubleshooting some issues we were having with Shippable , trying to get a bunch of our unit tests to run in parallel so that our builds would complete faster. I didn't care what order the different processes completed in, but I didn't want the shell script to exit until all the spawned unit test processes had exited. I ultimately wasn't able to satisfactorily solve the issue we were having, but I did learn more than I ever wanted to know about how to run processes in parallel in shell scripts. So here I shall impart unto you the knowledge I have gained. I hope someone else finds it useful!

Wait

The simplest way to achieve what I wanted was to use the wait command. You simply fork all of your processes with & , and then follow them with a wait command. Behold:

#!/bin/sh

/usr/bin/my-process-1 --args1 &
/usr/bin/my-process-2 --args2 &
/usr/bin/my-process-3 --args3 &

wait
echo all processes complete

It's really as easy as that. When you run the script, all three processes will be forked in parallel, and the script will wait until all three have completed before exiting. Anything after the wait command will execute only after the three forked processes have exited.

Pros

Damn, son! It doesn't get any simpler than that!

Cons

I don't think there's really any way to determine the exit codes of the processes you forked. That was a deal-breaker for my use case, since I needed to know if any of the tests failed and return an error code from the parent shell script if they did.

Another downside is that output from the processes will be all mish-mashed together, which makes it difficult to follow. In our situation, it was basically impossible to determine which unit tests had failed because they were all spewing their output at the same time.

GNU Parallel

There is a super nifty program called GNU Parallel that does exactly what I wanted. It works kind of like xargs in that you can give it a collection of arguments to pass to a single command which will all be run, only this will run them in parallel instead of in serial like xargs does (OR DOES IT??</foreshadowing>). It is super powerful, and all the different ways you can use it are beyond the scope of this article, but here's a rough equivalent to the example script above:

#!/bin/sh

parallel /usr/bin/my-process-{} --args{} ::: 1 2 3
echo all processes complete

The official "10 seconds installation" method for the latest version of GNU Parallel (from the README) is as follows:

(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash

Pros

If any of the processes returns a non-zero exit code, parallel will return a non-zero exit code. This means you can use $? in your shell script to detect if any of the processes failed. Nice! GNU Parallel also (by default) collates the output of each process together, so you'll see the complete output of each process as it completes instead of a mash-up of all the output combined together as it's produced. Also nice!

I am such a damn fanboy I might even buy an official GNU Parallel mug and t-shirt . Actually I'll probably save the money and get the new Star Wars Battlefront game when it comes out instead. But I did seriously consider the parallel schwag for a microsecond or so.

Cons

Literally none.

Xargs

So it turns out that our old friend xargs has supported parallel processing all along! Who knew? It's like the nerdy chick in the movies who gets a makeover near the end and it turns out she's even hotter than the stereotypical hot cheerleader chicks who were picking on her the whole time. Just pass it a -Pn argument and it will run your commands using up to n threads. Check out this mega-sexy equivalent to the above scripts:

#!/bin/sh

printf "1\n2\n3" | xargs -n1 -P3 -I{} /usr/bin/my-process-{} --args{}
echo all processes complete

Pros

xargs returns a non-zero exit code if any of the processes fails, so you can again use $? in your shell script to detect errors. The difference is it will return 123 , unlike GNU Parallel which passes through the non-zero exit code of the process that failed (I'm not sure how parallel picks if more than one process fails, but I'd assume it's either the first or last process to fail). Another pro is that xargs is most likely already installed on your preferred distribution of Linux.

Cons

I have read reports that the non-GNU version of xargs does not support parallel processing, so you may or may not be out of luck with this option if you're on AIX or a BSD or something.

xargs also has the same problem as the wait solution where the output from your processes will be all mixed together.

Another con is that xargs is a little less flexible than parallel in how you specify the processes to run. You have to pipe your values into it, and if you use the -I argument for string-replacement then your values have to be separated by newlines (which is more annoying when running it ad-hoc). It's still pretty nice, but nowhere near as flexible or powerful as parallel .

Also there's no place to buy an xargs mug and t-shirt. Lame!

And The Winner Is

After determining that the Shippable problem we were having was completely unrelated to the parallel scripting method I was using, I ended up sticking with parallel for my unit tests. Even though it meant one more dependency on our build machine, the ease

[Jun 23, 2018] bash - Shell Scripting Using xargs to execute parallel instances of a shell function

Jun 23, 2018 | stackoverflow.com

Gnats ,Jul 23, 2010 at 19:33

I'm trying to use xargs in a shell script to run parallel instances of a function I've defined in the same script. The function times the fetching of a page, and so it's important that the pages are actually fetched concurrently in parallel processes, and not in background processes (if my understanding of this is wrong and there's negligible difference between the two, just let me know).

The function is:

function time_a_url ()
{
     oneurltime=$($time_command -p wget -p $1 -O /dev/null 2>&1 1>/dev/null | grep real | cut -d" " -f2)
     echo "Fetching $1 took $oneurltime seconds."
}

How does one do this with an xargs pipe in a form that can take number of times to run time_a_url in parallel as an argument? And yes, I know about GNU parallel, I just don't have the privilege to install software where I'm writing this.

Dennis Williamson ,Jul 23, 2010 at 23:03

Here's a demo of how you might be able to get your function to work:
$ f() { echo "[$@]"; }
$ export -f f
$ echo -e "b 1\nc 2\nd 3 4" | xargs -P 0 -n 1 -I{} bash -c f\ \{\}
[b 1]
[d 3 4]
[c 2]

The keys to making this work are to export the function so the bash that xargs spawns will see it and to escape the space between the function name and the escaped braces. You should be able to adapt this to work in your situation. You'll need to adjust the arguments for -P and -n (or remove them) to suit your needs.

You can probably get rid of the grep and cut . If you're using the Bash builtin time , you can specify an output format using the TIMEFORMAT variable. If you're using GNU /usr/bin/time , you can use the --format argument. Either of these will allow you to drop the -p also.

You can replace this part of your wget command: 2>&1 1>/dev/null with -q . In any case, you have those reversed. The correct order would be >/dev/null 2>&1 .

Lee Netherton ,Aug 30, 2011 at 16:32

I used xargs -P0 -n1 -I{} bash -c "f {}" which still works, and seems a little tidier. – Lee Netherton Aug 30 '11 at 16:32

tmpvar ,Jul 24, 2010 at 15:21

On Mac OS X:

xargs: max. processes must be >0 (for: xargs -P [>0])

f() { echo "[$@]"; }
export -f f

echo -e "b 1\nc 2\nd 3 4" | sed 's/ /\\ /g' | xargs -P 10 -n 1 -I{} bash -c f\ \{\}

echo -e "b 1\nc 2\nd 3 4" | xargs -P 10 -I '{}' bash -c 'f "$@"' arg0 '{}'

,

If you install GNU Parallel on another system, you will see the functionality is in a single file (called parallel).

You should be able to simply copy that file to your own ~/bin.

[Jun 02, 2018] How to run Linux commands simultaneously with GNU Parallel

Jun 02, 2018 | www.techrepublic.com

Scratching the surface

We've only just scratched the surface of GNU Parallel. I highly recommend you give the official GNU Parallel tutorial a read, and watch this video tutorial series on Yutube , so you can understand the complexities of the tool (of which there are many).

But this will get you started on a path to helping your data center Linux servers use commands with more efficiency.

[Jun 02, 2018] GNU Parallel Examples

EXAMPLE: Working as xargs -n1. Argument appending

GNU parallel can work similar to xargs -n1.

To compress all html files using gzip run:

  find . -name '*.html' | parallel gzip --best

If the file names may contain a newline use -0. Substitute FOO BAR with FUBAR in all files in this dir and subdirs:

  find . -type f -print0 | parallel -q0 perl -i -pe 's/FOO BAR/FUBAR/g'

Note -q is needed because of the space in 'FOO BAR'.

EXAMPLE: Reading arguments from command line

GNU parallel can take the arguments from command line instead of stdin (standard input). To compress all html files in the current dir using gzip run:

  parallel gzip --best ::: *.html

To convert *.wav to *.mp3 using LAME running one process per CPU core run:

  parallel lame {} -o {.}.mp3 ::: *.wav
EXAMPLE: Inserting multiple arguments

When moving a lot of files like this: mv *.log destdir you will sometimes get the error:

  bash: /bin/mv: Argument list too long

because there are too many files. You can instead do:

  ls | grep -E '\.log$' | parallel mv {} destdir

This will run mv for each file. It can be done faster if mv gets as many arguments that will fit on the line:

  ls | grep -E '\.log$' | parallel -m mv {} destdir

In many shells you can also use printf:

  printf '%s\0' *.log | parallel -0 -m mv {} destdir
EXAMPLE: Context replace

To remove the files pict0000.jpg .. pict9999.jpg you could do:

  seq -w 0 9999 | parallel rm pict{}.jpg

You could also do:

  seq -w 0 9999 | perl -pe 's/(.*)/pict$1.jpg/' | parallel -m rm

The first will run rm 10000 times, while the last will only run rm as many times needed to keep the command line length short enough to avoid Argument list too long (it typically runs 1-2 times).

You could also run:

  seq -w 0 9999 | parallel -X rm pict{}.jpg

This will also only run rm as many times needed to keep the command line length short enough.

EXAMPLE: Compute intensive jobs and substitution

If ImageMagick is installed this will generate a thumbnail of a jpg file:

  convert -geometry 120 foo.jpg thumb_foo.jpg

This will run with number-of-cpu-cores jobs in parallel for all jpg files in a directory:

  ls *.jpg | parallel convert -geometry 120 {} thumb_{}

To do it recursively use find:

  find . -name '*.jpg' | parallel convert -geometry 120 {} {}_thumb.jpg

Notice how the argument has to start with {} as {} will include path (e.g. running convert -geometry 120 ./foo/bar.jpg thumb_./foo/bar.jpg would clearly be wrong). The command will generate files like ./foo/bar.jpg_thumb.jpg.

Use {.} to avoid the extra .jpg in the file name. This command will make files like ./foo/bar_thumb.jpg:

  find . -name '*.jpg' | parallel convert -geometry 120 {} {.}_thumb.jpg
EXAMPLE: Substitution and redirection

This will generate an uncompressed version of .gz-files next to the .gz-file:

  parallel zcat {} ">"{.} ::: *.gz

Quoting of > is necessary to postpone the redirection. Another solution is to quote the whole command:

  parallel "zcat {} >{.}" ::: *.gz

Other special shell characters (such as * ; $ > < | >> <<) also need to be put in quotes, as they may otherwise be interpreted by the shell and not given to GNU parallel.

EXAMPLE: Composed commands

A job can consist of several commands. This will print the number of files in each directory:

  ls | parallel 'echo -n {}" "; ls {}|wc -l'

To put the output in a file called <name>.dir:

  ls | parallel '(echo -n {}" "; ls {}|wc -l) >{}.dir'

Even small shell scripts can be run by GNU parallel:

  find . | parallel 'a={}; name=${a##*/};' \
    'upper=$(echo "$name" | tr "[:lower:]" "[:upper:]");'\
    'echo "$name - $upper"'

  ls | parallel 'mv {} "$(echo {} | tr "[:upper:]" "[:lower:]")"'

Given a list of URLs, list all URLs that fail to download. Print the line number and the URL.

  cat urlfile | parallel "wget {} 2>/dev/null || grep -n {} urlfile"

Create a mirror directory with the same filenames except all files and symlinks are empty files.

  cp -rs /the/source/dir mirror_dir
  find mirror_dir -type l | parallel -m rm {} '&&' touch {}

Find the files in a list that do not exist

  cat file_list | parallel 'if [ ! -e {} ] ; then echo {}; fi'
EXAMPLE: Composed command with multiple input sources

You have a dir with files named as 24 hours in 5 minute intervals: 00:00, 00:05, 00:10 .. 23:55. You want to find the files missing:

  parallel [ -f {1}:{2} ] "||" echo {1}:{2} does not exist \
    ::: {00..23} ::: {00..55..5}
EXAMPLE: Calling Bash functions

If the composed command is longer than a line, it becomes hard to read. In Bash you can use functions. Just remember to export -f the function.

  doit() {
    echo Doing it for $1
    sleep 2
    echo Done with $1
  }
  export -f doit
  parallel doit ::: 1 2 3

  doubleit() {
    echo Doing it for $1 $2
    sleep 2
    echo Done with $1 $2
  }
  export -f doubleit
  parallel doubleit ::: 1 2 3 ::: a b

To do this on remote servers you need to transfer the function using --env:

  parallel --env doit -S server doit ::: 1 2 3
  parallel --env doubleit -S server doubleit ::: 1 2 3 ::: a b

If your environment (aliases, variables, and functions) is small you can copy the full environment without having to export -f anything. See env_parallel.

EXAMPLE: Function tester

To test a program with different parameters:

  tester() {
    if (eval "$@") >&/dev/null; then
      perl -e 'printf "\033[30;102m[ OK ]\033[0m @ARGV\n"' "$@"
    else
      perl -e 'printf "\033[30;101m[FAIL]\033[0m @ARGV\n"' "$@"
    fi
  }
  export -f tester
  parallel tester my_program ::: arg1 arg2
  parallel tester exit ::: 1 0 2 0

If my_program fails a red FAIL will be printed followed by the failing command; otherwise a green OK will be printed followed by the command.

EXAMPLE: Log rotate

Log rotation renames a logfile to an extension with a higher number: log.1 becomes log.2, log.2 becomes log.3, and so on. The oldest log is removed. To avoid overwriting files the process starts backwards from the high number to the low number. This will keep 10 old versions of the log:

  seq 9 -1 1 | parallel -j1 mv log.{} log.'{= $_++ =}'
  mv log log.1
EXAMPLE: Removing file extension when processing files

When processing files removing the file extension using {.} is often useful.

Create a directory for each zip-file and unzip it in that dir:

  parallel 'mkdir {.}; cd {.}; unzip ../{}' ::: *.zip

Recompress all .gz files in current directory using bzip2 running 1 job per CPU core in parallel:

  parallel "zcat {} | bzip2 >{.}.bz2 && rm {}" ::: *.gz

Convert all WAV files to MP3 using LAME:

  find sounddir -type f -name '*.wav' | parallel lame {} -o {.}.mp3

Put all converted in the same directory:

  find sounddir -type f -name '*.wav' | \
    parallel lame {} -o mydir/{/.}.mp3
EXAMPLE: Removing strings from the argument

If you have directory with tar.gz files and want these extracted in the corresponding dir (e.g foo.tar.gz will be extracted in the dir foo) you can do:

  parallel --plus 'mkdir {..}; tar -C {..} -xf {}' ::: *.tar.gz

If you want to remove a different ending, you can use {%string}:

  parallel --plus echo {%_demo} ::: mycode_demo keep_demo_here

You can also remove a starting string with {#string}

  parallel --plus echo {#demo_} ::: demo_mycode keep_demo_here

To remove a string anywhere you can use regular expressions with {/regexp/replacement} and leave the replacement empty:

  parallel --plus echo {/demo_/} ::: demo_mycode remove_demo_here
EXAMPLE: Download 24 images for each of the past 30 days

Let us assume a website stores images like:

  http://www.example.com/path/to/YYYYMMDD_##.jpg

where YYYYMMDD is the date and ## is the number 01-24. This will download images for the past 30 days:

  getit() {
    date=$(date -d "today -$1 days" +%Y%m%d)
    num=$2
    echo wget http://www.example.com/path/to/${date}_${num}.jpg
  }
  export -f getit
  
  parallel getit ::: $(seq 30) ::: $(seq -w 24)

$(date -d "today -$1 days" +%Y%m%d) will give the dates in YYYYMMDD with $1 days subtracted.

EXAMPLE: Download world map from NASA

NASA provides tiles to download on earthdata.nasa.gov. Download tiles for Blue Marble world map and create a 10240x20480 map.

  base=https://map1a.vis.earthdata.nasa.gov/wmts-geo/wmts.cgi
  service="SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0"
  layer="LAYER=BlueMarble_ShadedRelief_Bathymetry"
  set="STYLE=&TILEMATRIXSET=EPSG4326_500m&TILEMATRIX=5"
  tile="TILEROW={1}&TILECOL={2}"
  format="FORMAT=image%2Fjpeg"
  url="$base?$service&$layer&$set&$tile&$format"

  parallel -j0 -q wget "$url" -O {1}_{2}.jpg ::: {0..19} ::: {0..39}
  parallel eval convert +append {}_{0..39}.jpg line{}.jpg ::: {0..19}
  convert -append line{0..19}.jpg world.jpg
EXAMPLE: Download Apollo-11 images from NASA using jq

Search NASA using their API to get JSON for images related to 'apollo 11' and has 'moon landing' in the description.

The search query returns JSON containing URLs to JSON containing collections of pictures. One of the pictures in each of these collection is large.

wget is used to get the JSON for the search query. jq is then used to extract the URLs of the collections. parallel then calls wget to get each collection, which is passed to jq to extract the URLs of all images. grep filters out the large images, and parallel finally uses wget to fetch the images.

  base="https://images-api.nasa.gov/search"
  q="q=apollo 11"
  description="description=moon landing"
  media_type="media_type=image"
  wget -O - "$base?$q&$description&$media_type" |
    jq -r .collection.items[].href |
    parallel wget -O - |
    jq -r .[] |
    grep large |
    parallel wget
EXAMPLE: Copy files as last modified date (ISO8601) with added random digits
  find . | parallel cp {} '../destdir/{= $a=int(10000*rand); $_=pQ($_);
    $_=`date -r "$_" +%FT%T"$a"`; chomp; =}'

{= and =} mark a perl expression. pQ quotes the string. date +%FT%T is the date in ISO8601 with time.

EXAMPLE: Digtal clock with "blinking" :

The : in a digital clock blinks. To make every other line have a ':' and the rest a ' ' a perl expression is used to look at the 3rd input source. If the value modudo 2 is 1: Use ":" otherwise use " ":

  parallel -k echo {1}'{=3 $_=$_%2?":":" "=}'{2}{3} \
    ::: {0..12} ::: {0..5} ::: {0..9}
EXAMPLE: Aggregating content of files

This:

  parallel --header : echo x{X}y{Y}z{Z} \> x{X}y{Y}z{Z} \
  ::: X {1..5} ::: Y {01..10} ::: Z {1..5}

will generate the files x1y01z1 .. x5y10z5. If you want to aggregate the output grouping on x and z you can do this:

  parallel eval 'cat {=s/y01/y*/=} > {=s/y01//=}' ::: *y01*

For all values of x and z it runs commands like:

  cat x1y*z1 > x1z1

So you end up with x1z1 .. x5z5 each containing the content of all values of y.

EXAMPLE: Breadth first parallel web crawler/mirrorer

This script below will crawl and mirror a URL in parallel. It downloads first pages that are 1 click down, then 2 clicks down, then 3; instead of the normal depth first, where the first link link on each page is fetched first.

Run like this:

  PARALLEL=-j100 ./parallel-crawl http://gatt.org.yeslab.org/

Remove the wget part if you only want a web crawler.

It works by fetching a page from a list of URLs and looking for links in that page that are within the same starting URL and that have not already been seen. These links are added to a new queue. When all the pages from the list is done, the new queue is moved to the list of URLs and the process is started over until no unseen links are found.

  #!/bin/bash

  # E.g. http://gatt.org.yeslab.org/
  URL=$1
  # Stay inside the start dir
  BASEURL=$(echo $URL | perl -pe 's:#.*::; s:(//.*/)[^/]*:$1:')
  URLLIST=$(mktemp urllist.XXXX)
  URLLIST2=$(mktemp urllist.XXXX)
  SEEN=$(mktemp seen.XXXX)

  # Spider to get the URLs
  echo $URL >$URLLIST
  cp $URLLIST $SEEN

  while [ -s $URLLIST ] ; do
    cat $URLLIST |
      parallel lynx -listonly -image_links -dump {} \; \
        wget -qm -l1 -Q1 {} \; echo Spidered: {} \>\&2 |
        perl -ne 's/#.*//; s/\s+\d+.\s(\S+)$/$1/ and
          do { $seen{$1}++ or print }' |
      grep -F $BASEURL |
      grep -v -x -F -f $SEEN | tee -a $SEEN > $URLLIST2
    mv $URLLIST2 $URLLIST
  done

  rm -f $URLLIST $URLLIST2 $SEEN
EXAMPLE: Process files from a tar file while unpacking

If the files to be processed are in a tar file then unpacking one file and processing it immediately may be faster than first unpacking all files.

  tar xvf foo.tgz | perl -ne 'print $l;$l=$_;END{print $l}' | \
    parallel echo

The Perl one-liner is needed to make sure the file is complete before handing it to GNU parallel.

EXAMPLE: Rewriting a for-loop and a while-read-loop

for-loops like this:

  (for x in `cat list` ; do
    do_something $x
  done) | process_output

and while-read-loops like this:

  cat list | (while read x ; do
    do_something $x
  done) | process_output

can be written like this:

  cat list | parallel do_something | process_output

For example: Find which host name in a list has IP address 1.2.3 4:

  cat hosts.txt | parallel -P 100 host | grep 1.2.3.4

If the processing requires more steps the for-loop like this:

  (for x in `cat list` ; do
    no_extension=${x%.*};
    do_step1 $x scale $no_extension.jpg
    do_step2 <$x $no_extension
  done) | process_output

and while-loops like this:

  cat list | (while read x ; do
    no_extension=${x%.*};
    do_step1 $x scale $no_extension.jpg
    do_step2 <$x $no_extension
  done) | process_output

can be written like this:

  cat list | parallel "do_step1 {} scale {.}.jpg ; do_step2 <{} {.}" |\
    process_output

If the body of the loop is bigger, it improves readability to use a function:

  (for x in `cat list` ; do
    do_something $x
    [... 100 lines that do something with $x ...]
  done) | process_output

  cat list | (while read x ; do
    do_something $x
    [... 100 lines that do something with $x ...]
  done) | process_output

can both be rewritten as:

  doit() {
    x=$1
    do_something $x
    [... 100 lines that do something with $x ...]
  }
  export -f doit
  cat list | parallel doit
EXAMPLE: Rewriting nested for-loops

Nested for-loops like this:

  (for x in `cat xlist` ; do
    for y in `cat ylist` ; do
      do_something $x $y
    done
  done) | process_output

can be written like this:

  parallel do_something {1} {2} :::: xlist ylist | process_output

Nested for-loops like this:

  (for colour in red green blue ; do
    for size in S M L XL XXL ; do
      echo $colour $size
    done
  done) | sort

can be written like this:

  parallel echo {1} {2} ::: red green blue ::: S M L XL XXL | sort
EXAMPLE: Finding the lowest difference between files

diff is good for finding differences in text files. diff | wc -l gives an indication of the size of the difference. To find the differences between all files in the current dir do:

  parallel --tag 'diff {1} {2} | wc -l' ::: * ::: * | sort -nk3

This way it is possible to see if some files are closer to other files.

EXAMPLE: for-loops with column names

When doing multiple nested for-loops it can be easier to keep track of the loop variable if is is named instead of just having a number. Use --header : to let the first argument be an named alias for the positional replacement string:

  parallel --header : echo {colour} {size} \
    ::: colour red green blue ::: size S M L XL XXL

This also works if the input file is a file with columns:

  cat addressbook.tsv | \
    parallel --colsep '\t' --header : echo {Name} {E-mail address}
EXAMPLE: All combinations in a list

GNU parallel makes all combinations when given two lists.

To make all combinations in a single list with unique values, you repeat the list and use replacement string with a Perl expression that skips the job if the value from input source 1 is greater than or equal to the value from input source 2:

  parallel echo {= 'if($arg[1] ge $arg[2]) { skip() }' =} ::: A B C D ::: A B C D

Or more generally:

  parallel echo \
    '{= for $t (2..$#arg){ if($arg[$t-1] ge $arg[$t]) { skip() } } =}' \
    ::: A B C D ::: A B C D ::: A B C D
EXAMPLE: From a to b and b to c

Assume you have input like:

  aardvark
  babble
  cab
  dab
  each

and want to run combinations like:

  aardvark babble
  babble cab
  cab dab
  dab each

If the input is in the file in.txt:

  parallel echo {1} - {2} ::::+ <(head -n -1 in.txt) <(tail -n +2 in.txt)

If the input is in the array $a here are two solutions:

  seq $((${#a[@]}-1)) | env_parallel --env a echo '${a[{=$_--=}]} - ${a[{}]}'
  parallel echo {1} - {2} ::: "${a[@]::${#a[@]}-1}" :::+ "${a[@]:1}"
EXAMPLE: Count the differences between all files in a dir

Using --results the results are saved in /tmp/diffcount*.

  parallel --results /tmp/diffcount "diff -U 0 {1} {2} | \
    tail -n +3 |grep -v '^@'|wc -l" ::: * ::: *

To see the difference between file A and file B look at the file '/tmp/diffcount/1/A/2/B'.

EXAMPLE: Speeding up fast jobs

Starting a job on the local machine takes around 10 ms. This can be a big overhead if the job takes very few ms to run. Often you can group small jobs together using -X which will make the overhead less significant. Compare the speed of these:

  seq -w 0 9999 | parallel touch pict{}.jpg
  seq -w 0 9999 | parallel -X touch pict{}.jpg

If your program cannot take multiple arguments, then you can use GNU parallel to spawn multiple GNU parallels:

  seq -w 0 9999999 |
    parallel -j10 -q -I,, --pipe parallel -j0 touch pict{}.jpg

If -j0 normally spawns 252 jobs, then the above will try to spawn 2520 jobs. On a normal GNU/Linux system you can spawn 32000 jobs using this technique with no problems. To raise the 32000 jobs limit raise /proc/sys/kernel/pid_max to 4194303.

EXAMPLE: Using shell variables

When using shell variables you need to quote them correctly as they may otherwise be interpreted by the shell.

Notice the difference between:

  ARR=("My brother's 12\" records are worth <\$\$\$>"'!' Foo Bar)
  parallel echo ::: ${ARR[@]} # This is probably not what you want

and:

  ARR=("My brother's 12\" records are worth <\$\$\$>"'!' Foo Bar)
  parallel echo ::: "${ARR[@]}"

When using variables in the actual command that contains special characters (e.g. space) you can quote them using '"$VAR"' or using "'s and -q:

  VAR="My brother's 12\" records are worth <\$\$\$>"
  parallel -q echo "$VAR" ::: '!'
  export VAR
  parallel echo '"$VAR"' ::: '!'

If $VAR does not contain ' then "'$VAR'" will also work (and does not need export):

  VAR="My 12\" records are worth <\$\$\$>"
  parallel echo "'$VAR'" ::: '!'

If you use them in a function you just quote as you normally would do:

  VAR="My brother's 12\" records are worth <\$\$\$>"
  export VAR
  myfunc() { echo "$VAR" "$1"; }
  export -f myfunc
  parallel myfunc ::: '!'
EXAMPLE: Group output lines

When running jobs that output data, you often do not want the output of multiple jobs to run together. GNU parallel defaults to grouping the output of each job, so the output is printed when the job finishes. If you want full lines to be printed while the job is running you can use --line-buffer. If you want output to be printed as soon as possible you can use -u.

Compare the output of:

  parallel wget --limit-rate=100k \
    https://ftpmirror.gnu.org/parallel/parallel-20{}0822.tar.bz2 \
    ::: {12..16}
  parallel --line-buffer wget --limit-rate=100k \
    https://ftpmirror.gnu.org/parallel/parallel-20{}0822.tar.bz2 \
    ::: {12..16}
  parallel -u wget --limit-rate=100k \
    https://ftpmirror.gnu.org/parallel/parallel-20{}0822.tar.bz2 \
    ::: {12..16}
EXAMPLE: Tag output lines

GNU parallel groups the output lines, but it can be hard to see where the different jobs begin. --tag prepends the argument to make that more visible:

  parallel --tag wget --limit-rate=100k \
    https://ftpmirror.gnu.org/parallel/parallel-20{}0822.tar.bz2 \
    ::: {12..16}

--tag works with --line-buffer but not with -u:

  parallel --tag --line-buffer wget --limit-rate=100k \
    https://ftpmirror.gnu.org/parallel/parallel-20{}0822.tar.bz2 \
    ::: {12..16}

Check the uptime of the servers in ~/.parallel/sshloginfile:

  parallel --tag -S .. --nonall uptime
EXAMPLE: Colorize output

Give each job a new color. Most terminals support ANSI colors with the escape code "\033[30;3Xm" where 0 <= X <= 7:

    parallel --tagstring '\033[30;3{=$_=++$::color%8=}m' seq {} ::: {1..10}
    parallel --rpl '{color} $_="\033[30;3".(++$::color%8)."m"' \
      --tagstring {color} seq {} ::: {1..10}

To get rid of the initial \t (which comes from --tagstring):

    ... | perl -pe 's/\t//'
EXAMPLE: Keep order of output same as order of input

Normally the output of a job will be printed as soon as it completes. Sometimes you want the order of the output to remain the same as the order of the input. This is often important, if the output is used as input for another system. -k will make sure the order of output will be in the same order as input even if later jobs end before earlier jobs.

Append a string to every line in a text file:

  cat textfile | parallel -k echo {} append_string

If you remove -k some of the lines may come out in the wrong order.

Another example is traceroute:

  parallel traceroute ::: qubes-os.org debian.org freenetproject.org

will give traceroute of qubes-os.org, debian.org and freenetproject.org, but it will be sorted according to which job completed first.

To keep the order the same as input run:

  parallel -k traceroute ::: qubes-os.org debian.org freenetproject.org

This will make sure the traceroute to qubes-os.org will be printed first.

A bit more complex example is downloading a huge file in chunks in parallel: Some internet connections will deliver more data if you download files in parallel. For downloading files in parallel see: "EXAMPLE: Download 10 images for each of the past 30 days". But if you are downloading a big file you can download the file in chunks in parallel.

To download byte 10000000-19999999 you can use curl:

  curl -r 10000000-19999999 http://example.com/the/big/file >file.part

To download a 1 GB file we need 100 10MB chunks downloaded and combined in the correct order.

  seq 0 99 | parallel -k curl -r \
    {}0000000-{}9999999 http://example.com/the/big/file > file
EXAMPLE: Parallel grep

grep -r greps recursively through directories. On multicore CPUs GNU parallel can often speed this up.

  find . -type f | parallel -k -j150% -n 1000 -m grep -H -n STRING {}

This will run 1.5 job per core, and give 1000 arguments to grep.

EXAMPLE: Grepping n lines for m regular expressions.

The simplest solution to grep a big file for a lot of regexps is:

  grep -f regexps.txt bigfile

Or if the regexps are fixed strings:

  grep -F -f regexps.txt bigfile

There are 3 limiting factors: CPU, RAM, and disk I/O.

RAM is easy to measure: If the grep process takes up most of your free memory (e.g. when running top), then RAM is a limiting factor.

CPU is also easy to measure: If the grep takes >90% CPU in top, then the CPU is a limiting factor, and parallelization will speed this up.

It is harder to see if disk I/O is the limiting factor, and depending on the disk system it may be faster or slower to parallelize. The only way to know for certain is to test and measure.

Limiting factor: RAM

The normal grep -f regexs.txt bigfile works no matter the size of bigfile, but if regexps.txt is so big it cannot fit into memory, then you need to split this.

grep -F takes around 100 bytes of RAM and grep takes about 500 bytes of RAM per 1 byte of regexp. So if regexps.txt is 1% of your RAM, then it may be too big.

If you can convert your regexps into fixed strings do that. E.g. if the lines you are looking for in bigfile all looks like:

  ID1 foo bar baz Identifier1 quux
  fubar ID2 foo bar baz Identifier2

then your regexps.txt can be converted from:

  ID1.*Identifier1
  ID2.*Identifier2

into:

  ID1 foo bar baz Identifier1
  ID2 foo bar baz Identifier2

This way you can use grep -F which takes around 80% less memory and is much faster.

If it still does not fit in memory you can do this:

  parallel --pipepart -a regexps.txt --block 1M grep -Ff - -n bigfile |
    sort -un | perl -pe 's/^\d+://'

The 1M should be your free memory divided by the number of cores and divided by 200 for grep -F and by 1000 for normal grep. On GNU/Linux you can do:

  free=$(awk '/^((Swap)?Cached|MemFree|Buffers):/ { sum += $2 }
              END { print sum }' /proc/meminfo)
  percpu=$((free / 200 / $(parallel --number-of-cores)))k

  parallel --pipepart -a regexps.txt --block $percpu --compress \
    grep -F -f - -n bigfile |
    sort -un | perl -pe 's/^\d+://'

If you can live with duplicated lines and wrong order, it is faster to do:

  parallel --pipepart -a regexps.txt --block $percpu --compress \
    grep -F -f - bigfile

Limiting factor: CPU

If the CPU is the limiting factor parallelization should be done on the regexps:

  cat regexp.txt | parallel --pipe -L1000 --round-robin --compress \
    grep -f - -n bigfile |
    sort -un | perl -pe 's/^\d+://'

The command will start one grep per CPU and read bigfile one time per CPU, but as that is done in parallel, all reads except the first will be cached in RAM. Depending on the size of regexp.txt it may be faster to use --block 10m instead of -L1000.

Some storage systems perform better when reading multiple chunks in parallel. This is true for some RAID systems and for some network file systems. To parallelize the reading of bigfile:

  parallel --pipepart --block 100M -a bigfile -k --compress \
    grep -f regexp.txt

This will split bigfile into 100MB chunks and run grep on each of these chunks. To parallelize both reading of bigfile and regexp.txt combine the two using --fifo:

  parallel --pipepart --block 100M -a bigfile --fifo cat regexp.txt \
    \| parallel --pipe -L1000 --round-robin grep -f - {}

If a line matches multiple regexps, the line may be duplicated.

Bigger problem

If the problem is too big to be solved by this, you are probably ready for Lucene.

EXAMPLE: Using remote computers

To run commands on a remote computer SSH needs to be set up and you must be able to login without entering a password (The commands ssh-copy-id, ssh-agent, and sshpass may help you do that).

If you need to login to a whole cluster, you typically do not want to accept the host key for every host. You want to accept them the first time and be warned if they are ever changed. To do that:

  # Add the servers to the sshloginfile
  (echo servera; echo serverb) > .parallel/my_cluster
  # Make sure .ssh/config exist
  touch .ssh/config
  cp .ssh/config .ssh/config.backup
  # Disable StrictHostKeyChecking temporarily
  (echo 'Host *'; echo StrictHostKeyChecking no) >> .ssh/config
  parallel --slf my_cluster --nonall true
  # Remove the disabling of StrictHostKeyChecking
  mv .ssh/config.backup .ssh/config

The servers in .parallel/my_cluster are now added in .ssh/known_hosts.

To run echo on server.example.com:

  seq 10 | parallel --sshlogin server.example.com echo

To run commands on more than one remote computer run:

  seq 10 | parallel --sshlogin server.example.com,server2.example.net echo

Or:

  seq 10 | parallel --sshlogin server.example.com \
    --sshlogin server2.example.net echo

If the login username is foo on server2.example.net use:

  seq 10 | parallel --sshlogin server.example.com \
    --sshlogin [email protected] echo

If your list of hosts is server1-88.example.net with login foo:

  seq 10 | parallel -Sfoo@server{1..88}.example.net echo

To distribute the commands to a list of computers, make a file mycomputers with all the computers:

  server.example.com
  [email protected]
  server3.example.com

Then run:

  seq 10 | parallel --sshloginfile mycomputers echo

To include the local computer add the special sshlogin ':' to the list:

  server.example.com
  [email protected]
  server3.example.com
  :

GNU parallel will try to determine the number of CPU cores on each of the remote computers, and run one job per CPU core - even if the remote computers do not have the same number of CPU cores.

If the number of CPU cores on the remote computers is not identified correctly the number of CPU cores can be added in front. Here the computer has 8 CPU cores.

  seq 10 | parallel --sshlogin 8/server.example.com echo
EXAMPLE: Transferring of files

To recompress gzipped files with bzip2 using a remote computer run:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com \
    --transfer "zcat {} | bzip2 -9 >{.}.bz2"

This will list the .gz-files in the logs directory and all directories below. Then it will transfer the files to server.example.com to the corresponding directory in $HOME/logs. On server.example.com the file will be recompressed using zcat and bzip2 resulting in the corresponding file with .gz replaced with .bz2.

If you want the resulting bz2-file to be transferred back to the local computer add --return {.}.bz2:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com \
    --transfer --return {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"

After the recompressing is done the .bz2-file is transferred back to the local computer and put next to the original .gz-file.

If you want to delete the transferred files on the remote computer add --cleanup. This will remove both the file transferred to the remote computer and the files transferred from the remote computer:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com \
    --transfer --return {.}.bz2 --cleanup "zcat {} | bzip2 -9 >{.}.bz2"

If you want run on several computers add the computers to --sshlogin either using ',' or multiple --sshlogin:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com,server2.example.com \
    --sshlogin server3.example.com \
    --transfer --return {.}.bz2 --cleanup "zcat {} | bzip2 -9 >{.}.bz2"

You can add the local computer using --sshlogin :. This will disable the removing and transferring for the local computer only:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com,server2.example.com \
    --sshlogin server3.example.com \
    --sshlogin : \
    --transfer --return {.}.bz2 --cleanup "zcat {} | bzip2 -9 >{.}.bz2"

Often --transfer, --return and --cleanup are used together. They can be shortened to --trc:

  find logs/ -name '*.gz' | \
    parallel --sshlogin server.example.com,server2.example.com \
    --sshlogin server3.example.com \
    --sshlogin : \
    --trc {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"

With the file mycomputers containing the list of computers it becomes:

  find logs/ -name '*.gz' | parallel --sshloginfile mycomputers \
    --trc {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"

If the file ~/.parallel/sshloginfile contains the list of computers the special short hand -S .. can be used:

  find logs/ -name '*.gz' | parallel -S .. \
    --trc {.}.bz2 "zcat {} | bzip2 -9 >{.}.bz2"
EXAMPLE: Distributing work to local and remote computers

Convert *.mp3 to *.ogg running one process per CPU core on local computer and server2:

  parallel --trc {.}.ogg -S server2,: \
    'mpg321 -w - {} | oggenc -q0 - -o {.}.ogg' ::: *.mp3
EXAMPLE: Running the same command on remote computers

To run the command uptime on remote computers you can do:

  parallel --tag --nonall -S server1,server2 uptime

--nonall reads no arguments. If you have a list of jobs you want to run on each computer you can do:

  parallel --tag --onall -S server1,server2 echo ::: 1 2 3

Remove --tag if you do not want the sshlogin added before the output.

If you have a lot of hosts use '-j0' to access more hosts in parallel.

EXAMPLE: Using remote computers behind NAT wall

If the workers are behind a NAT wall, you need some trickery to get to them.

If you can ssh to a jumphost, and reach the workers from there, then the obvious solution would be this, but it does not work:

  parallel --ssh 'ssh jumphost ssh' -S host1 echo ::: DOES NOT WORK

It does not work because the command is dequoted by ssh twice where as GNU parallel only expects it to be dequoted once.

So instead put this in ~/.ssh/config:

  Host host1 host2 host3
    ProxyCommand ssh jumphost.domain nc -w 1 %h 22

It requires nc(netcat) to be installed on jumphost. With this you can simply:

  parallel -S host1,host2,host3 echo ::: This does work

No jumphost, but port forwards

If there is no jumphost but each server has port 22 forwarded from the firewall (e.g. the firewall's port 22001 = port 22 on host1, 22002 = host2, 22003 = host3) then you can use ~/.ssh/config:

  Host host1.v
    Port 22001
  Host host2.v
    Port 22002
  Host host3.v
    Port 22003
  Host *.v
    Hostname firewall

And then use host{1..3}.v as normal hosts:

  parallel -S host1.v,host2.v,host3.v echo ::: a b c

No jumphost, no port forwards

If ports cannot be forwarded, you need some sort of VPN to traverse the NAT-wall. TOR is one options for that, as it is very easy to get working.

You need to install TOR and setup a hidden service. In torrc put:

  HiddenServiceDir /var/lib/tor/hidden_service/
  HiddenServicePort 22 127.0.0.1:22

Then start TOR: /etc/init.d/tor restart

The TOR hostname is now in /var/lib/tor/hidden_service/hostname and is something similar to izjafdceobowklhz.onion. Now you simply prepend torsocks to ssh:

  parallel --ssh 'torsocks ssh' -S izjafdceobowklhz.onion \
    -S zfcdaeiojoklbwhz.onion,auclucjzobowklhi.onion echo ::: a b c

If not all hosts are accessible through TOR:

  parallel -S 'torsocks ssh izjafdceobowklhz.onion,host2,host3' \
    echo ::: a b c

See more ssh tricks on https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Proxies_and_Jump_Hosts

EXAMPLE: Parallelizing rsync

rsync is a great tool, but sometimes it will not fill up the available bandwidth. This is often a problem when copying several big files over high speed connections.

The following will start one rsync per big file in src-dir to dest-dir on the server fooserver:

  cd src-dir; find . -type f -size +100000 | \
    parallel -v ssh fooserver mkdir -p /dest-dir/{//}\; \
      rsync -s -Havessh {} fooserver:/dest-dir/{}

The dirs created may end up with wrong permissions and smaller files are not being transferred. To fix those run rsync a final time:

  rsync -Havessh src-dir/ fooserver:/dest-dir/

If you are unable to push data, but need to pull them and the files are called digits.png (e.g. 000000.png) you might be able to do:

  seq -w 0 99 | parallel rsync -Havessh fooserver:src/*{}.png destdir/
EXAMPLE: Use multiple inputs in one command

Copy files like foo.es.ext to foo.ext:

  ls *.es.* | perl -pe 'print; s/\.es//' | parallel -N2 cp {1} {2}

The perl command spits out 2 lines for each input. GNU parallel takes 2 inputs (using -N2) and replaces {1} and {2} with the inputs.

Count in binary:

  parallel -k echo ::: 0 1 ::: 0 1 ::: 0 1 ::: 0 1 ::: 0 1 ::: 0 1

Print the number on the opposing sides of a six sided die:

  parallel --link -a <(seq 6) -a <(seq 6 -1 1) echo
  parallel --link echo :::: <(seq 6) <(seq 6 -1 1)

Convert files from all subdirs to PNG-files with consecutive numbers (useful for making input PNG's for ffmpeg):

  parallel --link -a <(find . -type f | sort) \
    -a <(seq $(find . -type f|wc -l)) convert {1} {2}.png

Alternative version:

  find . -type f | sort | parallel convert {} {#}.png
EXAMPLE: Use a table as input

Content of table_file.tsv:

  foo<TAB>bar
  baz <TAB> quux

To run:

  cmd -o bar -i foo
  cmd -o quux -i baz

you can run:

  parallel -a table_file.tsv --colsep '\t' cmd -o {2} -i {1}

Note: The default for GNU parallel is to remove the spaces around the columns. To keep the spaces:

  parallel -a table_file.tsv --trim n --colsep '\t' cmd -o {2} -i {1}
EXAMPLE: Output to database

GNU parallel can output to a database table and a CSV-file:

  DBURL=csv:///%2Ftmp%2Fmy.csv
  DBTABLEURL=$DBURL/mytable
  parallel --sqlandworker $DBTABLEURL seq ::: {1..10}

It is rather slow and takes up a lot of CPU time because GNU parallel parses the whole CSV file for each update.

A better approach is to use an SQLite-base and then convert that to CSV:

  DBURL=sqlite3:///%2Ftmp%2Fmy.sqlite
  DBTABLEURL=$DBURL/mytable
  parallel --sqlandworker $DBTABLEURL seq ::: {1..10}
  sql $DBURL '.headers on' '.mode csv' 'SELECT * FROM mytable;'

This takes around a second per job.

If you have access to a real database system, such as PostgreSQL, it is even faster:

  DBURL=pg://user:pass@host/mydb
  DBTABLEURL=$DBURL/mytable
  parallel --sqlandworker $DBTABLEURL seq ::: {1..10}
  sql $DBURL "COPY (SELECT * FROM mytable) TO stdout DELIMITER ',' CSV HEADER;"

Or MySQL:

  DBURL=mysql://user:pass@host/mydb
  DBTABLEURL=$DBURL/mytable
  parallel --sqlandworker $DBTABLEURL seq ::: {1..10}
  sql -p -B $DBURL "SELECT * FROM mytable;" > mytable.tsv
  perl -pe 's/"/""/g; s/\t/","/g; s/^/"/; s/$/"/; s/\\\\/\\/g;
    s/\\t/\t/g; s/\\n/\n/g;' mytable.tsv
EXAMPLE: Output to CSV-file for R

If you have no need for the advanced job distribution control that a database provides, but you simply want output into a CSV file that you can read into R or LibreCalc, then you can use --results:

  parallel --results my.csv seq ::: 10 20 30
  R
  > mydf <- read.csv("my.csv");
  > print(mydf[2,])
  > write(as.character(mydf[2,c("Stdout")]),'')
EXAMPLE: Use XML as input

The show Aflyttet on Radio 24syv publishes an RSS feed with their audio podcasts on: http://arkiv.radio24syv.dk/audiopodcast/channel/4466232

Using xpath you can extract the URLs for 2016 and download them using GNU parallel:

  wget -O - http://arkiv.radio24syv.dk/audiopodcast/channel/4466232 |
    xpath -e "//ancestor::pubDate[contains(text(),'2016')]/../enclosure/@url" |
    parallel -u wget '{= s/ url="//; s/"//; =}'
EXAMPLE: Run the same command 10 times

If you want to run the same command with the same arguments 10 times in parallel you can do:

  seq 10 | parallel -n0 my_command my_args
EXAMPLE: Working as cat | sh. Resource inexpensive jobs and evaluation

GNU parallel can work similar to cat | sh.

A resource inexpensive job is a job that takes very little CPU, disk I/O and network I/O. Ping is an example of a resource inexpensive job. wget is too - if the webpages are small.

The content of the file jobs_to_run:

  ping -c 1 10.0.0.1
  wget http://example.com/status.cgi?ip=10.0.0.1
  ping -c 1 10.0.0.2
  wget http://example.com/status.cgi?ip=10.0.0.2
  ...
  ping -c 1 10.0.0.255
  wget http://example.com/status.cgi?ip=10.0.0.255

To run 100 processes simultaneously do:

  parallel -j 100 < jobs_to_run

As there is not a command the jobs will be evaluated by the shell.

EXAMPLE: Processing a big file using more cores

To process a big file or some output you can use --pipe to split up the data into blocks and pipe the blocks into the processing program.

If the program is gzip -9 you can do:

  cat bigfile | parallel --pipe --recend '' -k gzip -9 > bigfile.gz

This will split bigfile into blocks of 1 MB and pass that to gzip -9 in parallel. One gzip will be run per CPU core. The output of gzip -9 will be kept in order and saved to bigfile.gz

gzip works fine if the output is appended, but some processing does not work like that - for example sorting. For this GNU parallel can put the output of each command into a file. This will sort a big file in parallel:

  cat bigfile | parallel --pipe --files sort |\
    parallel -Xj1 sort -m {} ';' rm {} >bigfile.sort

Here bigfile is split into blocks of around 1MB, each block ending in '\n' (which is the default for --recend). Each block is passed to sort and the output from sort is saved into files. These files are passed to the second parallel that runs sort -m on the files before it removes the files. The output is saved to bigfile.sort.

GNU parallel's --pipe maxes out at around 100 MB/s because every byte has to be copied through GNU parallel. But if bigfile is a real (seekable) file GNU parallel can by-pass the copying and send the parts directly to the program:

  parallel --pipepart --block 100m -a bigfile --files sort |\
    parallel -Xj1 sort -m {} ';' rm {} >bigfile.sort
EXAMPLE: Grouping input lines

When processing with --pipe you may have lines grouped by a value. Here is my.csv:

   Transaction Customer Item
        1       a       53
        2       b       65
        3       b       82
        4       c       96
        5       c       67
        6       c       13
        7       d       90
        8       d       43
        9       d       91
        10      d       84
        11      e       72
        12      e       102
        13      e       63
        14      e       56
        15      e       74

Let us assume you want GNU parallel to process each customer. In other words: You want all the transactions for a single customer to be treated as a single record.

To do this we preprocess the data with a program that inserts a record separator before each customer (column 2 = $F[1]). Here we first make a 50 character random string, which we then use as the separator:

  sep=`perl -e 'print map { ("a".."z","A".."Z")[rand(52)] } (1..50);'`
  cat my.csv | perl -ape '$F[1] ne $l and print "'$sep'"; $l = $F[1]' |
     parallel --recend $sep --rrs --pipe -N1 wc

If your program can process multiple customers replace -N1 with a reasonable --blocksize.

EXAMPLE: Running more than 250 jobs workaround

If you need to run a massive amount of jobs in parallel, then you will likely hit the filehandle limit which is often around 250 jobs. If you are super user you can raise the limit in /etc/security/limits.conf but you can also use this workaround. The filehandle limit is per process. That means that if you just spawn more GNU parallels then each of them can run 250 jobs. This will spawn up to 2500 jobs:

  cat myinput |\
    parallel --pipe -N 50 --round-robin -j50 parallel -j50 your_prg

This will spawn up to 62500 jobs (use with caution - you need 64 GB RAM to do this, and you may need to increase /proc/sys/kernel/pid_max):

  cat myinput |\
    parallel --pipe -N 250 --round-robin -j250 parallel -j250 your_prg
EXAMPLE: Working as mutex and counting semaphore

The command sem is an alias for parallel --semaphore.

A counting semaphore will allow a given number of jobs to be started in the background. When the number of jobs are running in the background, GNU sem will wait for one of these to complete before starting another command. sem --wait will wait for all jobs to complete.

Run 10 jobs concurrently in the background:

  for i in *.log ; do
    echo $i
    sem -j10 gzip $i ";" echo done
  done
  sem --wait

A mutex is a counting semaphore allowing only one job to run. This will edit the file myfile and prepends the file with lines with the numbers 1 to 3.

  seq 3 | parallel sem sed -i -e '1i{}' myfile

As myfile can be very big it is important only one process edits the file at the same time.

Name the semaphore to have multiple different semaphores active at the same time:

  seq 3 | parallel sem --id mymutex sed -i -e '1i{}' myfile
EXAMPLE: Mutex for a script

Assume a script is called from cron or from a web service, but only one instance can be run at a time. With sem and --shebang-wrap the script can be made to wait for other instances to finish. Here in bash:

  #!/usr/bin/sem --shebang-wrap -u --id $0 --fg /bin/bash
  
  echo This will run
  sleep 5
  echo exclusively

Here perl:

  #!/usr/bin/sem --shebang-wrap -u --id $0 --fg /usr/bin/perl
  
  print "This will run ";
  sleep 5;
  print "exclusively\n";

Here python:

  #!/usr/local/bin/sem --shebang-wrap -u --id $0 --fg /usr/bin/python
  
  import time
  print "This will run ";
  time.sleep(5)
  print "exclusively";
EXAMPLE: Start editor with filenames from stdin (standard input)

You can use GNU parallel to start interactive programs like emacs or vi:

  cat filelist | parallel --tty -X emacs
  cat filelist | parallel --tty -X vi

If there are more files than will fit on a single command line, the editor will be started again with the remaining files.

EXAMPLE: Running sudo

sudo requires a password to run a command as root. It caches the access, so you only need to enter the password again if you have not used sudo for a while.

The command:

  parallel sudo echo ::: This is a bad idea

is no good, as you would be prompted for the sudo password for each of the jobs. You can either do:

  sudo echo This
  parallel sudo echo ::: is a good idea

or:

  sudo parallel echo ::: This is a good idea

This way you only have to enter the sudo password once.

EXAMPLE: GNU Parallel as queue system/batch manager

GNU parallel can work as a simple job queue system or batch manager. The idea is to put the jobs into a file and have GNU parallel read from that continuously. As GNU parallel will stop at end of file we use tail to continue reading:

  true >jobqueue; tail -n+0 -f jobqueue | parallel

To submit your jobs to the queue:

  echo my_command my_arg >> jobqueue

You can of course use -S to distribute the jobs to remote computers:

  true >jobqueue; tail -n+0 -f jobqueue | parallel -S ..

If you keep this running for a long time, jobqueue will grow. A way of removing the jobs already run is by making GNU parallel stop when it hits a special value and then restart. To use --eof to make GNU parallel exit, tail also needs to be forced to exit:

  true >jobqueue;
  while true; do
    tail -n+0 -f jobqueue |
      (parallel -E StOpHeRe -S ..; echo GNU Parallel is now done;
       perl -e 'while(<>){/StOpHeRe/ and last};print <>' jobqueue > j2;
       (seq 1000 >> jobqueue &);
       echo Done appending dummy data forcing tail to exit)
    echo tail exited;
    mv j2 jobqueue
  done

In some cases you can run on more CPUs and computers during the night:

  # Day time
  echo 50% > jobfile
  cp day_server_list ~/.parallel/sshloginfile
  # Night time
  echo 100% > jobfile
  cp night_server_list ~/.parallel/sshloginfile
  tail -n+0 -f jobqueue | parallel --jobs jobfile -S ..

GNU Parallel discovers if jobfile or ~/.parallel/sshloginfile changes.

There is a a small issue when using GNU parallel as queue system/batch manager: You have to submit JobSlot number of jobs before they will start, and after that you can submit one at a time, and job will start immediately if free slots are available. Output from the running or completed jobs are held back and will only be printed when JobSlots more jobs has been started (unless you use --ungroup or --line-buffer, in which case the output from the jobs are printed immediately). E.g. if you have 10 jobslots then the output from the first completed job will only be printed when job 11 has started, and the output of second completed job will only be printed when job 12 has started.

EXAMPLE: GNU Parallel as dir processor

If you have a dir in which users drop files that needs to be processed you can do this on GNU/Linux (If you know what inotifywait is called on other platforms file a bug report):

  inotifywait -qmre MOVED_TO -e CLOSE_WRITE --format %w%f my_dir |\
    parallel -u echo

This will run the command echo on each file put into my_dir or subdirs of my_dir.

You can of course use -S to distribute the jobs to remote computers:

  inotifywait -qmre MOVED_TO -e CLOSE_WRITE --format %w%f my_dir |\
    parallel -S ..  -u echo

If the files to be processed are in a tar file then unpacking one file and processing it immediately may be faster than first unpacking all files. Set up the dir processor as above and unpack into the dir.

Using GNU Parallel as dir processor has the same limitations as using GNU Parallel as queue system/batch manager.

EXAMPLE: Locate the missing package

If you have downloaded source and tried compiling it, you may have seen:

  $ ./configure
  [...]
  checking for something.h... no
  configure: error: "libsomething not found"

Often it is not obvious which package you should install to get that file. Debian has `apt-file` to search for a file. `tracefile` from https://gitlab.com/ole.tange/tangetools can tell which files a program tried to access. In this case we are interested in one of the last files:

  $ tracefile -un ./configure | tail | parallel -j0 apt-file search
QUOTING

GNU parallel is very liberal in quoting. You only need to quote characters that have special meaning in shell:

  ( ) $ ` ' " < > ; | \

and depending on context these needs to be quoted, too:

  ~ & # ! ? space * {

Therefore most people will never need more quoting than putting '\' in front of the special characters.

Often you can simply put \' around every ':

  perl -ne '/^\S+\s+\S+$/ and print $ARGV,"\n"' file

can be quoted:

  parallel perl -ne \''/^\S+\s+\S+$/ and print $ARGV,"\n"'\' ::: file

However, when you want to use a shell variable you need to quote the $-sign. Here is an example using $PARALLEL_SEQ. This variable is set by GNU parallel itself, so the evaluation of the $ must be done by the sub shell started by GNU parallel:

  seq 10 | parallel -N2 echo seq:\$PARALLEL_SEQ arg1:{1} arg2:{2}

If the variable is set before GNU parallel starts you can do this:

  VAR=this_is_set_before_starting
  echo test | parallel echo {} $VAR

Prints: test this_is_set_before_starting

It is a little more tricky if the variable contains more than one space in a row:

  VAR="two  spaces  between  each  word"
  echo test | parallel echo {} \'"$VAR"\'

Prints: test two spaces between each word

If the variable should not be evaluated by the shell starting GNU parallel but be evaluated by the sub shell started by GNU parallel, then you need to quote it:

  echo test | parallel VAR=this_is_set_after_starting \; echo {} \$VAR

Prints: test this_is_set_after_starting

It is a little more tricky if the variable contains space:

  echo test |\
    parallel VAR='"two  spaces  between  each  word"' echo {} \'"$VAR"\'

Prints: test two spaces between each word

$$ is the shell variable containing the process id of the shell. This will print the process id of the shell running GNU parallel:

  seq 10 | parallel echo $$

And this will print the process ids of the sub shells started by GNU parallel.

  seq 10 | parallel echo \$\$

If the special characters should not be evaluated by the sub shell then you need to protect it against evaluation from both the shell starting GNU parallel and the sub shell:

  echo test | parallel echo {} \\\$VAR

Prints: test $VAR

GNU parallel can protect against evaluation by the sub shell by using -q:

  echo test | parallel -q echo {} \$VAR

Prints: test $VAR

This is particularly useful if you have lots of quoting. If you want to run a perl script like this:

  perl -ne '/^\S+\s+\S+$/ and print $ARGV,"\n"' file

It needs to be quoted like one of these:

  ls | parallel perl -ne '/^\\S+\\s+\\S+\$/\ and\ print\ \$ARGV,\"\\n\"'
  ls | parallel perl -ne \''/^\S+\s+\S+$/ and print $ARGV,"\n"'\'

Notice how spaces, \'s, "'s, and $'s need to be quoted. GNU parallel can do the quoting by using option -q:

  ls | parallel -q  perl -ne '/^\S+\s+\S+$/ and print $ARGV,"\n"'

However, this means you cannot make the sub shell interpret special characters. For example because of -q this WILL NOT WORK:

  ls *.gz | parallel -q "zcat {} >{.}"
  ls *.gz | parallel -q "zcat {} | bzip2 >{.}.bz2"

because > and | need to be interpreted by the sub shell.

If you get errors like:

  sh: -c: line 0: syntax error near unexpected token
  sh: Syntax error: Unterminated quoted string
  sh: -c: line 0: unexpected EOF while looking for matching `''
  sh: -c: line 1: syntax error: unexpected end of file
  zsh:1: no matches found:

then you might try using -q.

If you are using bash process substitution like <(cat foo) then you may try -q and prepending command with bash -c:

  ls | parallel -q bash -c 'wc -c <(echo {})'

Or for substituting output:

  ls | parallel -q bash -c \
    'tar c {} | tee >(gzip >{}.tar.gz) | bzip2 >{}.tar.bz2'

Conclusion: To avoid dealing with the quoting problems it may be easier just to write a small script or a function (remember to export -f the function) and have GNU parallel call that.

LIST RUNNING JOBS

If you want a list of the jobs currently running you can run:

  killall -USR1 parallel

GNU parallel will then print the currently running jobs on stderr (standard error).

COMPLETE RUNNING JOBS BUT DO NOT START NEW JOBS

If you regret starting a lot of jobs you can simply break GNU parallel, but if you want to make sure you do not have half-completed jobs you should send the signal SIGTERM to GNU parallel:

  killall -TERM parallel

This will tell GNU parallel to not start any new jobs, but wait until the currently running jobs are finished before exiting.

ENVIRONMENT VARIABLES
$PARALLEL_HOME
Dir where GNU parallel stores config files, semaphores, and caches information between invocations. Default: $HOME/.parallel.
$PARALLEL_PID
The environment variable $PARALLEL_PID is set by GNU parallel and is visible to the jobs started from GNU parallel. This makes it possible for the jobs to communicate directly to GNU parallel. Remember to quote the $, so it gets evaluated by the correct shell.

Example: If each of the jobs tests a solution and one of jobs finds the solution the job can tell GNU parallel not to start more jobs by: kill -TERM $PARALLEL_PID. This only works on the local computer.

$PARALLEL_RSYNC_OPTS
Options to pass on to rsync. Defaults to: -rlDzR.
$PARALLEL_SHELL
Use this shell for the commands run by GNU Parallel:
  • $PARALLEL_SHELL. If undefined use:
  • The shell that started GNU Parallel. If that cannot be determined:
  • $SHELL. If undefined use:
  • /bin/sh
$PARALLEL_SSH
GNU parallel defaults to using ssh for remote access. This can be overridden with $PARALLEL_SSH, which again can be overridden with --ssh. It can also be set on a per server basis (see --sshlogin).
$PARALLEL_SEQ
$PARALLEL_SEQ will be set to the sequence number of the job running. Remember to quote the $, so it gets evaluated by the correct shell.

Example:

  seq 10 | parallel -N2 \
    echo seq:'$'PARALLEL_SEQ arg1:{1} arg2:{2}
$PARALLEL_TMUX
Path to tmux. If unset the tmux in $PATH is used.
$TMPDIR
Directory for temporary files. See: --tmpdir.
$PARALLEL
The environment variable $PARALLEL will be used as default options for GNU parallel. If the variable contains special shell characters (e.g. $, *, or space) then these need to be to be escaped with \.

Example:

  cat list | parallel -j1 -k -v ls
  cat list | parallel -j1 -k -v -S"myssh user@server" ls

can be written as:

  cat list | PARALLEL="-kvj1" parallel ls
  cat list | PARALLEL='-kvj1 -S myssh\ user@server' \
    parallel echo

Notice the \ in the middle is needed because 'myssh' and 'user@server' must be one argument.

DEFAULT PROFILE (CONFIG FILE)

The global configuration file /etc/parallel/config, followed by user configuration file ~/.parallel/config (formerly known as .parallelrc) will be read in turn if they exist. Lines starting with '#' will be ignored. The format can follow that of the environment variable $PARALLEL, but it is often easier to simply put each option on its own line.

Options on the command line take precedence, followed by the environment variable $PARALLEL, user configuration file ~/.parallel/config, and finally the global configuration file /etc/parallel/config.

Note that no file that is read for options, nor the environment variable $PARALLEL, may contain retired options such as --tollef.

PROFILE FILES

If --profile set, GNU parallel will read the profile from that file rather than the global or user configuration files. You can have multiple --profiles.

Example: Profile for running a command on every sshlogin in ~/.ssh/sshlogins and prepend the output with the sshlogin:

  echo --tag -S .. --nonall > ~/.parallel/n
  parallel -Jn uptime

Example: Profile for running every command with -j-1 and nice

  echo -j-1 nice > ~/.parallel/nice_profile
  parallel -J nice_profile bzip2 -9 ::: *

Example: Profile for running a perl script before every command:

  echo "perl -e '\$a=\$\$; print \$a,\" \",'\$PARALLEL_SEQ',\" \";';" \
    > ~/.parallel/pre_perl
  parallel -J pre_perl echo ::: *

Note how the $ and " need to be quoted using \.

Example: Profile for running distributed jobs with nice on the remote computers:

  echo -S .. nice > ~/.parallel/dist
  parallel -J dist --trc {.}.bz2 bzip2 -9 ::: *

[Apr 30, 2013] GNU Parallel The Command-Line Power Tool USENIX by Ole Tange

login: VOL. 36, NO. 1

... ... ...

Your First Parallel Job

GNU Parallel is available as a package for most UNIX distributions.See http:// www.gnu.org/s/parallel if it is not obvious how to install it on your system.After installation find a bunch of files on your computer and gzip them in parallel:

parallel gzip ::: *

Here your shell expands * to the files, ::: tells GNU Parallel to read arguments from the command line, and gzip is the command to run.The jobs are then run in parallel.After you have gziped the files, you can recompress them with bzip2:

parallel "zcat {} | bzip2 >{.}.bz2" ::: *

Here {} is being replaced with the file name.The output from zcat is piped to bzip2, which then compresses the output.The {.} is the file name with its extension stripped (e.g., foo.gz becomes foo), so the output from file.gz is stored in file.bz2.

GNU Parallel tries to be very liberal in quoting, so the above could also be written:

parallel zcat {} "|" bzip2 ">"{.}.bz2 ::: *

Only the chars that have special meaning in shell need to be quoted.

Reading Input

As we have seen, input can be given on the command line.Input can also be piped into GNU Parallel:

find . -type f | parallel gzip

GNU Parallel uses newline as a record separator and deals correctly with file names containing a word space or a dot.If you have normal users on your system, you will have experienced file names like these.If your users are really mean and write file names containing newlines, you can use NULL as a record separator:

find . -type f -print0 | parallel -0 gzip

You can read from a file using -a:

parallel -a filelist gzip

If you use more than one -a, a line from each input file will be available as {#}:

parallel -a sourcelist -a destlist gzip {1} ">"{2}

The same goes if you read a specific number of arguments at a time using -N:

cat filelist | parallel -N 3 diff {1} {2} ">" {3}

If your input is in columns you can split the columns using --colsep:

cat filelist.tsv | parallel --colsep '\t' diff {1} {2} ">" {3}

--colsep is a regexp, so you can match more advanced column separators.

Building the Command to Run

Just like xargs, GNU Parallel can take multiple input lines and put those on the same line.Compare these:

ls *.gz | parallel mv {} archive

ls *.gz | parallel -X mv {} archive

The first will run mv for every .gz file, whereas the second will fit as many files into {} as possible before running.

The {} can be put anywhere in the command, but if it is part of a word, that word will be repeated when using -X:

(echo 1; echo 2) | parallel -X echo foo bar{}baz quux

will repeat bar-baz and print:

foo bar1baz bar2baz quux

If you do not give a command to run, GNU Parallel will assume the input lines are command lines and run those in parallel:

(echo ls; echo grep root /etc/passwd) | parallel

;login: FEBRUARY 2011 GNU Parallel: The Command-Line Power Tool 4344 ;login: VOL. 36, NO. 1

Controlling the Output

One of the problems with running jobs in parallel is making sure the output of the running commands do not get mixed up.traceroute is a good example of this as it prints out slowly and parallel traceroutes will get mixed up.Try:

traceroute foss.org.my & traceroute debian.org & traceroute freenetproject.org & wait

and compare the output to:

parallel traceroute ::: foss.org.my debian.org freenetproject.org

As you can see, GNU Parallel only prints out when a job is done-thereby making sure the output is never mixed with other jobs.If you insist, GNU Parallel can give you the output immediately with -u, but output from different jobs may mix.

For some input, you want the output to come in the same order as the input.-k does that for you:

parallel -k echo {}';' sleep {} ::: 3 2 1 4

This will run the four commands in parallel, but postpone the output of the two middle commands until the first is finished.

Execution of the Jobs

GNU Parallel defaults to run one job per CPU core in parallel.You can change this with -j.You can put an integer as the number of jobs (e.g., -j 4 for four jobs in parallel) or you can put a percentage of the number of CPU cores (e.g., -j 200% to run two jobs per CPU core):

parallel -j200% gzip ::: *

If you pass -j a file name, the parameter will be read from that file:

parallel -j /tmp/number_of_jobs_to_run gzip ::: *

The file will be read again after each job finishes.This way you can change the number of jobs running during a parallel run.This is particularly useful if it is a very long run and you need to prioritize other tasks on the computer.

To list the currently running jobs you need to send GNU Parallel SIGUSR1:

killall -USR1 parallel

GNU Parallel will then print the currently running jobs on STDERR.

If you regret starting a lot of jobs, you can simply break GNU Parallel, but if you want to make sure you do not have half-completed jobs, you should send the signal SIGTERM to GNU Parallel:

killall -TERM parallel

This will tell GNU Parallel not to start any new jobs but to wait until the currently running jobs are finished before exiting.

When monitoring the progress on screen it is often nice to have the output prepended with the command that was run.-v will do that for you:

parallel -v gzip ::: *

If you want to monitor the progress as it goes you can also use --progress and --eta:

parallel --progress gzip ::: *

parallel --eta gzip ::: *

This is especially useful for debugging when jobs run on remote computers.

Remote Computers

GNU Parallel can use the CPU power of remote computers to help do computations. As an example, we will recompress .gz files into .bz2 files, but you can just as easily do other compute-intensive jobs such as video encoding or image transformation.

You will need to be able to log in to the remote host using ssh without entering a password (ssh-agent may be handy for that).To transfer files, rsync needs to be installed, and to help GNU Parallel figure out how many CPU cores each computer has, GNU Parallel should also be installed on the remote computers.

Try this simple example to see that your setup is working:

parallel --sshlogin yourserver.example.com hostname';' echo {} ::: 1 2 3

This should print out the hostname of your server three times, each followed by the numbers 1 2 3.--sshlogin can be shortened to -S. To use more than one server, do:

parallel -S yourserver.example.com,server2.example.net 
	hostname';' echo {} ::: 1 2 3

If you have a different login name, just prepend login@ to the server name-just as you would with ssh.You can also give more than one -S instead of using a comma:

parallel -S yourserver.example.com -S [email protected] 
	hostname';' echo {} ::: 1 2 3

The special sshlogin ':' is your local computer:

parallel -S yourserver.example.com -S [email protected] -S : 
	hostname';' echo {} ::: 1 2 3

In this case you may see that GNU Parallel runs all three jobs on your local computer ,because the jobs are so fast to run.

If you have a file containing a list of the sshlogins to use, you can tell GNU Parallel to use that file:

parallel --sshloginfile mylistofsshlogins hostname';' echo {} ::: 1 2 3

The special sshlogin ..will read the sshloginfile ~/.parallel/sshloginfile:

parallel -S .. hostname';' echo {} ::: 1 2 3

Transferring Files

If your servers are not sharing storage (using NFS or something similar), you often need to transfer the files to be processed to the remote computers and the results back to the local computer.

To transfer a file to a remote computer, you will use --transfer:

parallel -S .. --transfer gzip '< {} | wc -c' ::: *.txt

;login: FEBRUARY 2011 GNU Parallel: The Command-Line Power Tool 4546 ;login: VOL. 36, NO. 1

Here we transfer each of the .txt files to the remote servers, compress them, and count how many bytes they now take up.

After a transfer you often will want to remove the transferred file from the remote computers.--cleanup does that for you:

parallel -S .. --transfer --cleanup gzip '< {} | wc -c' ::: *.txt

When processing files the result is often a file that you want copied back, after which the transferred and the result file should be removed from the remote computers:

parallel -S .. --transfer --return {.}.bz2 --cleanup zcat '< {} | bzip2 >{.}.bz2' ::: *.gz

Here the .gz files will be transferred and then recompressed using zcat and bzip2.The resulting .bz2 file is transferred back, and the .gz and the .bz2 files are removed from the remote computers.The combination --transfer --cleanup --return foo is used so often that it has its own abbreviation: --trc foo.

You can specify multiple --trc if your command generates multiple result files.

GNU Parallel will try to detect the number of cores on remote computers and run one job per CPU core even if the computers have different number of CPU cores:

parallel -S .. --trc {.}.bz2 zcat '< {} | bzip2 >{.}.bz2' ::: *.gz

GNU Parallel as Part of a Script

The more you practice using GNU Parallel, the more places you will see it can be useful.Every time you write a for loop or a while-read loop, consider if this could be done in parallel.Often the for loop can completely be replaced with a single line using GNU Parallel; if the jobs you want to run in parallel are very complex, you may want to make a script and have GNU Parallel call that script.Occasionally your for loop is so complex that neither of these is an option.

This is where parallel --semaphore can help you out.sem is the short alias for parallel --semaphore.

for i in `ls *.log` ; do

[... a lot of complex lines here ...]

sem -j4 --id my_id do_work $i

done

sem --wait --id my_id

This will run do_work in the background until four jobs are running.Then sem will wait until one of the four jobs has finished before starting another job.The last line (sem --wait) pauses the script until all the jobs started by sem have finished.my_id is a unique string used by sem to identify this script, since you may have other sems running at the same time.If you only run sem from one script at a time, --id my_id can be left out.

A special case is sem -j1, which works like a mutex and is useful if you only want one program running at a time.

GNU Parallel as a Job Queue Manager

With a few lines of code, GNU Parallel can work as a job queue manager:

echo >jobqueue; tail -f jobqueue | parallel

To submit your jobs to the queue, do:

echo my_command my_arg >> jobqueue

You can, of course, use -S to distribute the jobs to remote computers:

echo >jobqueue; tail -f jobqueue | parallel -S ..

If you have a dir into which users drop files that need to be processed, you can do this on GNU/Linux:

inotifywait -q -m -r -e CLOSE_WRITE --format %w%f my_dir | parallel -u echo

This will run the command echo on each file put into my_dir or subdirs of my_dir.Here again you can use -S to distribute the jobs to remote computers:

inotifywait -q -m -r -e CLOSE_WRITE --format %w%f my_dir | parallel -S .. -u echo

See You on the Mailing List

I hope you have thought of situations where GNU Parallel can be of benefit to you.If you like GNU Parallel please let others know about it through email lists, forums, blogs, and social networks.If GNU Parallel saves you money, please donate to the FSF https://my.fsf.org/donate.If you have questions about GNU Parallel, join the mailing list at http://lists.gnu.org/mailman/listinfo/parallel.

;login: FEBRUARY 2011 GNU Parallel: The Command-Line Power Tool 47\Ole Tange works in bioinformatics in Copenhagen. He is active in the free software community and is best known for his "patented Web shop" that shows the dangers of software patents (http:// ole.tange.dk/swpat). He will be happy to go to your conference to give a talk about GNU Parallel. [email protected]

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

GNU Parallel - GNU Project - Free Software Foundation

GNU Parallel tutorial

GNU Parallel The Command-Line Power Tool USENIX

Login. February 2011, Volume 36, Number 1 Authors: Ole Tange 105438-Tange.pdf<

Downloading GNU Parallel

GNU parallel can be found on the main GNU ftp server: http://ftp.gnu.org/gnu/parallel/ (via HTTP) and ftp://ftp.gnu.org/gnu/parallel/ (via FTP). It can also be found on the GNU mirrors; please use a mirror if possible.

Official packages exist for:

Community maintained packages:

Documentation

Just like other GNU software GNU parallel has documentation available online:

  • You can get a description of the design decisions behind GNU parallel by running man parallel_design.You may also find more information about GNU parallel by looking at /usr/doc/parallel/, /usr/local/doc/parallel/, or similar directories on your system.

    Some short videos displaying the most common usage are available at: http://www.youtube.com/playlist?list=PL284C9FF2488BC6D1.

    The history of GNU parallel can be found at http://www.gnu.org/software/parallel/history.html.

    The package includes GNU env_parallel, GNU sem, GNU parcat, GNU parset, GNU sql, and GNU niceload.



  • Etc

    Society

    Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

    Quotes

    War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

    Bulletin:

    Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

    History:

    Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

    Classic books:

    The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

    Most popular humor pages:

    Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

    The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


    Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

    FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

    This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

    You can use PayPal to to buy a cup of coffee for authors of this site

    Disclaimer:

    The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

    Last modified: February 19, 2020