Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

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
  username@server2.example.com
  8/my-8-core-server.example.com
  2/my_other_username@my-dualcore.example.net
  # 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 foo@server2.example.net echo

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

  server.example.com
  foo@server2.example.com
  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
  foo@server2.example.com
  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 ;-)

[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 mylogin@server2.example.net 
	hostname';' echo {} ::: 1 2 3

The special sshlogin ':' is your local computer:

parallel -S yourserver.example.com -S mylogin@server2.example.net -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. ole@tange.dk

Recommended Links

Softpanorama hot topic of the month

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

    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 in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

    ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

    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


    Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

    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.

    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 make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

    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 author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

    Last modified: September 12, 2017