.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "PARALLEL_EXAMPLES 7" .TH PARALLEL_EXAMPLES 7 2024-03-22 20240222 parallel .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "GNU PARALLEL EXAMPLES" .IX Header "GNU PARALLEL EXAMPLES" .SS "EXAMPLE: Working as xargs \-n1. Argument appending" .IX Subsection "EXAMPLE: Working as xargs -n1. Argument appending" GNU \fBparallel\fR can work similar to \fBxargs \-n1\fR. .PP To compress all html files using \fBgzip\fR run: .PP .Vb 1 \& find . \-name \*(Aq*.html\*(Aq | parallel gzip \-\-best .Ve .PP If the file names may contain a newline use \fB\-0\fR. Substitute FOO BAR with FUBAR in all files in this dir and subdirs: .PP .Vb 2 \& find . \-type f \-print0 | \e \& parallel \-q0 perl \-i \-pe \*(Aqs/FOO BAR/FUBAR/g\*(Aq .Ve .PP Note \fB\-q\fR is needed because of the space in 'FOO BAR'. .SS "EXAMPLE: Simple network scanner" .IX Subsection "EXAMPLE: Simple network scanner" \&\fBprips\fR can generate IP-addresses from CIDR notation. With GNU \&\fBparallel\fR you can build a simple network scanner to see which addresses respond to \fBping\fR: .PP .Vb 3 \& prips 130.229.16.0/20 | \e \& parallel \-\-timeout 2 \-j0 \e \& \*(Aqping \-c 1 {} >/dev/null && echo {}\*(Aq 2>/dev/null .Ve .SS "EXAMPLE: Reading arguments from command line" .IX Subsection "EXAMPLE: Reading arguments from command line" GNU \fBparallel\fR can take the arguments from command line instead of stdin (standard input). To compress all html files in the current dir using \fBgzip\fR run: .PP .Vb 1 \& parallel gzip \-\-best ::: *.html .Ve .PP To convert *.wav to *.mp3 using LAME running one process per CPU run: .PP .Vb 1 \& parallel lame {} \-o {.}.mp3 ::: *.wav .Ve .SS "EXAMPLE: Inserting multiple arguments" .IX Subsection "EXAMPLE: Inserting multiple arguments" When moving a lot of files like this: \fBmv *.log destdir\fR you will sometimes get the error: .PP .Vb 1 \& bash: /bin/mv: Argument list too long .Ve .PP because there are too many files. You can instead do: .PP .Vb 1 \& ls | grep \-E \*(Aq\e.log$\*(Aq | parallel mv {} destdir .Ve .PP This will run \fBmv\fR for each file. It can be done faster if \fBmv\fR gets as many arguments that will fit on the line: .PP .Vb 1 \& ls | grep \-E \*(Aq\e.log$\*(Aq | parallel \-m mv {} destdir .Ve .PP In many shells you can also use \fBprintf\fR: .PP .Vb 1 \& printf \*(Aq%s\e0\*(Aq *.log | parallel \-0 \-m mv {} destdir .Ve .SS "EXAMPLE: Context replace" .IX Subsection "EXAMPLE: Context replace" To remove the files \fIpict0000.jpg\fR .. \fIpict9999.jpg\fR you could do: .PP .Vb 1 \& seq \-w 0 9999 | parallel rm pict{}.jpg .Ve .PP You could also do: .PP .Vb 1 \& seq \-w 0 9999 | perl \-pe \*(Aqs/(.*)/pict$1.jpg/\*(Aq | parallel \-m rm .Ve .PP The first will run \fBrm\fR 10000 times, while the last will only run \&\fBrm\fR as many times needed to keep the command line length short enough to avoid \fBArgument list too long\fR (it typically runs 1\-2 times). .PP You could also run: .PP .Vb 1 \& seq \-w 0 9999 | parallel \-X rm pict{}.jpg .Ve .PP This will also only run \fBrm\fR as many times needed to keep the command line length short enough. .SS "EXAMPLE: Compute intensive jobs and substitution" .IX Subsection "EXAMPLE: Compute intensive jobs and substitution" If ImageMagick is installed this will generate a thumbnail of a jpg file: .PP .Vb 1 \& convert \-geometry 120 foo.jpg thumb_foo.jpg .Ve .PP This will run with number-of-cpus jobs in parallel for all jpg files in a directory: .PP .Vb 1 \& ls *.jpg | parallel convert \-geometry 120 {} thumb_{} .Ve .PP To do it recursively use \fBfind\fR: .PP .Vb 2 \& find . \-name \*(Aq*.jpg\*(Aq | \e \& parallel convert \-geometry 120 {} {}_thumb.jpg .Ve .PP Notice how the argument has to start with \fB{}\fR as \fB{}\fR will include path (e.g. running \fBconvert \-geometry 120 ./foo/bar.jpg thumb_./foo/bar.jpg\fR would clearly be wrong). The command will generate files like ./foo/bar.jpg_thumb.jpg. .PP Use \fB{.}\fR to avoid the extra .jpg in the file name. This command will make files like ./foo/bar_thumb.jpg: .PP .Vb 2 \& find . \-name \*(Aq*.jpg\*(Aq | \e \& parallel convert \-geometry 120 {} {.}_thumb.jpg .Ve .SS "EXAMPLE: Substitution and redirection" .IX Subsection "EXAMPLE: Substitution and redirection" This will generate an uncompressed version of .gz\-files next to the .gz\-file: .PP .Vb 1 \& parallel zcat {} ">"{.} ::: *.gz .Ve .PP Quoting of > is necessary to postpone the redirection. Another solution is to quote the whole command: .PP .Vb 1 \& parallel "zcat {} >{.}" ::: *.gz .Ve .PP 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 \fBparallel\fR. .SS "EXAMPLE: Composed commands" .IX Subsection "EXAMPLE: Composed commands" A job can consist of several commands. This will print the number of files in each directory: .PP .Vb 1 \& ls | parallel \*(Aqecho \-n {}" "; ls {}|wc \-l\*(Aq .Ve .PP To put the output in a file called .dir: .PP .Vb 1 \& ls | parallel \*(Aq(echo \-n {}" "; ls {}|wc \-l) >{}.dir\*(Aq .Ve .PP Even small shell scripts can be run by GNU \fBparallel\fR: .PP .Vb 3 \& find . | parallel \*(Aqa={}; name=${a##*/};\*(Aq \e \& \*(Aqupper=$(echo "$name" | tr "[:lower:]" "[:upper:]");\*(Aq\e \& \*(Aqecho "$name \- $upper"\*(Aq \& \& ls | parallel \*(Aqmv {} "$(echo {} | tr "[:upper:]" "[:lower:]")"\*(Aq .Ve .PP Given a list of URLs, list all URLs that fail to download. Print the line number and the URL. .PP .Vb 1 \& cat urlfile | parallel "wget {} 2>/dev/null || grep \-n {} urlfile" .Ve .PP Create a mirror directory with the same file names except all files and symlinks are empty files. .PP .Vb 2 \& cp \-rs /the/source/dir mirror_dir \& find mirror_dir \-type l | parallel \-m rm {} \*(Aq&&\*(Aq touch {} .Ve .PP Find the files in a list that do not exist .PP .Vb 1 \& cat file_list | parallel \*(Aqif [ ! \-e {} ] ; then echo {}; fi\*(Aq .Ve .SS "EXAMPLE: Composed command with perl replacement string" .IX Subsection "EXAMPLE: Composed command with perl replacement string" You have a bunch of file. You want them sorted into dirs. The dir of each file should be named the first letter of the file name. .PP .Vb 1 \& parallel \*(Aqmkdir \-p {=s/(.).*/$1/=}; mv {} {=s/(.).*/$1/=}\*(Aq ::: * .Ve .SS "EXAMPLE: Composed command with multiple input sources" .IX Subsection "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: .PP .Vb 2 \& parallel [ \-f {1}:{2} ] "||" echo {1}:{2} does not exist \e \& ::: {00..23} ::: {00..55..5} .Ve .SS "EXAMPLE: Calling Bash functions" .IX Subsection "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 \fBexport \-f\fR the function. .PP .Vb 7 \& 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 .Ve .PP To do this on remote servers you need to transfer the function using \&\fB\-\-env\fR: .PP .Vb 2 \& parallel \-\-env doit \-S server doit ::: 1 2 3 \& parallel \-\-env doubleit \-S server doubleit ::: 1 2 3 ::: a b .Ve .PP If your environment (aliases, variables, and functions) is small you can copy the full environment without having to \&\fBexport \-f\fR anything. See \fBenv_parallel\fR. .SS "EXAMPLE: Function tester" .IX Subsection "EXAMPLE: Function tester" To test a program with different parameters: .PP .Vb 10 \& tester() { \& if (eval "$@") >&/dev/null; then \& perl \-e \*(Aqprintf "\e033[30;102m[ OK ]\e033[0m @ARGV\en"\*(Aq "$@" \& else \& perl \-e \*(Aqprintf "\e033[30;101m[FAIL]\e033[0m @ARGV\en"\*(Aq "$@" \& fi \& } \& export \-f tester \& parallel tester my_program ::: arg1 arg2 \& parallel tester exit ::: 1 0 2 0 .Ve .PP If \fBmy_program\fR fails a red FAIL will be printed followed by the failing command; otherwise a green OK will be printed followed by the command. .SS "EXAMPLE: Identify few failing jobs" .IX Subsection "EXAMPLE: Identify few failing jobs" \&\fB\-\-bar\fR works best if jobs have no output. If the failing jobs have output you can identify the jobs like this: .PP .Vb 10 \& job\-with\-few\-failures() { \& # Force reproducibility \& RANDOM=$1 \& # This fails 1% (328 of 32768) \& if [ $RANDOM \-lt 328 ] ; then \& echo Failed $1 \& fi \& } \& export \-f job\-with\-few\-failures \& seq 1000 | parallel \-\-bar \-\-tag job\-with\-few\-failures .Ve .SS "EXAMPLE: Continously show the latest line of output" .IX Subsection "EXAMPLE: Continously show the latest line of output" It can be useful to monitor the output of running jobs. .PP This shows the most recent output line until a job finishes. After which the output of the job is printed in full: .PP .Vb 2 \& parallel \*(Aq{} | tee >(cat >&3)\*(Aq ::: \*(Aqcommand 1\*(Aq \*(Aqcommand 2\*(Aq \e \& 3> >(perl \-ne \*(Aq$|=1;chomp;printf"%.\*(Aq$COLUMNS\*(Aqs\er",$_." "x100\*(Aq) .Ve .SS "EXAMPLE: Log rotate" .IX Subsection "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: .PP .Vb 2 \& seq 9 \-1 1 | parallel \-j1 mv log.{} log.\*(Aq{= $_++ =}\*(Aq \& mv log log.1 .Ve .SS "EXAMPLE: Removing file extension when processing files" .IX Subsection "EXAMPLE: Removing file extension when processing files" When processing files removing the file extension using \fB{.}\fR is often useful. .PP Create a directory for each zip-file and unzip it in that dir: .PP .Vb 1 \& parallel \*(Aqmkdir {.}; cd {.}; unzip ../{}\*(Aq ::: *.zip .Ve .PP Recompress all .gz files in current directory using \fBbzip2\fR running 1 job per CPU in parallel: .PP .Vb 1 \& parallel "zcat {} | bzip2 >{.}.bz2 && rm {}" ::: *.gz .Ve .PP Convert all WAV files to MP3 using LAME: .PP .Vb 1 \& find sounddir \-type f \-name \*(Aq*.wav\*(Aq | parallel lame {} \-o {.}.mp3 .Ve .PP Put all converted in the same directory: .PP .Vb 2 \& find sounddir \-type f \-name \*(Aq*.wav\*(Aq | \e \& parallel lame {} \-o mydir/{/.}.mp3 .Ve .SS "EXAMPLE: Replacing parts of file names" .IX Subsection "EXAMPLE: Replacing parts of file names" If you deal with paired end reads, you will have files like barcode1_R1.fq.gz, barcode1_R2.fq.gz, barcode2_R1.fq.gz, and barcode2_R2.fq.gz. .PP You want barcode\fIN\fR_R1 to be processed with barcode\fIN\fR_R2. .PP .Vb 1 \& parallel \-\-plus myprocess {} {/_R1.fq.gz/_R2.fq.gz} ::: *_R1.fq.gz .Ve .PP If the barcode does not contain '_R1', you can do: .PP .Vb 1 \& parallel \-\-plus myprocess {} {/_R1/_R2} ::: *_R1.fq.gz .Ve .SS "EXAMPLE: Removing strings from the argument" .IX Subsection "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: .PP .Vb 1 \& parallel \-\-plus \*(Aqmkdir {..}; tar \-C {..} \-xf {}\*(Aq ::: *.tar.gz .Ve .PP If you want to remove a different ending, you can use {%string}: .PP .Vb 1 \& parallel \-\-plus echo {%_demo} ::: mycode_demo keep_demo_here .Ve .PP You can also remove a starting string with {#string} .PP .Vb 1 \& parallel \-\-plus echo {#demo_} ::: demo_mycode keep_demo_here .Ve .PP To remove a string anywhere you can use regular expressions with {/regexp/replacement} and leave the replacement empty: .PP .Vb 1 \& parallel \-\-plus echo {/demo_/} ::: demo_mycode remove_demo_here .Ve .SS "EXAMPLE: Download 24 images for each of the past 30 days" .IX Subsection "EXAMPLE: Download 24 images for each of the past 30 days" Let us assume a website stores images like: .PP .Vb 1 \& https://www.example.com/path/to/YYYYMMDD_##.jpg .Ve .PP where YYYYMMDD is the date and ## is the number 01\-24. This will download images for the past 30 days: .PP .Vb 6 \& getit() { \& date=$(date \-d "today \-$1 days" +%Y%m%d) \& num=$2 \& echo wget https://www.example.com/path/to/${date}_${num}.jpg \& } \& export \-f getit \& \& parallel getit ::: $(seq 30) ::: $(seq \-w 24) .Ve .PP \&\fB$(date \-d "today \-$1 days" +%Y%m%d)\fR will give the dates in YYYYMMDD with \fR\f(CB$1\fR\fB\fR days subtracted. .SS "EXAMPLE: Download world map from NASA" .IX Subsection "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. .PP .Vb 7 \& 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 .Ve .SS "EXAMPLE: Download Apollo\-11 images from NASA using jq" .IX Subsection "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. .PP The search query returns JSON containing URLs to JSON containing collections of pictures. One of the pictures in each of these collection is \fIlarge\fR. .PP \&\fBwget\fR is used to get the JSON for the search query. \fBjq\fR is then used to extract the URLs of the collections. \fBparallel\fR then calls \&\fBwget\fR to get each collection, which is passed to \fBjq\fR to extract the URLs of all images. \fBgrep\fR filters out the \fIlarge\fR images, and \&\fBparallel\fR finally uses \fBwget\fR to fetch the images. .PP .Vb 10 \& 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 .Ve .SS "EXAMPLE: Download video playlist in parallel" .IX Subsection "EXAMPLE: Download video playlist in parallel" \&\fByoutube-dl\fR is an excellent tool to download videos. It can, however, not download videos in parallel. This takes a playlist and downloads 10 videos in parallel. .PP .Vb 5 \& url=\*(Aqyoutu.be/watch?v=0wOf2Fgi3DE&list=UU_cznB5YZZmvAmeq7Y3EriQ\*(Aq \& export url \& youtube\-dl \-\-flat\-playlist "https://$url" | \& parallel \-\-tagstring {#} \-\-lb \-j10 \e \& youtube\-dl \-\-playlist\-start {#} \-\-playlist\-end {#} \*(Aq"https://$url"\*(Aq .Ve .SS "EXAMPLE: Prepend last modified date (ISO8601) to file name" .IX Subsection "EXAMPLE: Prepend last modified date (ISO8601) to file name" .Vb 2 \& parallel mv {} \*(Aq{= $a=pQ($_); $b=$_;\*(Aq \e \& \*(Aq$_=qx{date \-r "$a" +%FT%T}; chomp; $_="$_ $b" =}\*(Aq ::: * .Ve .PP \&\fB{=\fR and \fB=}\fR mark a perl expression. \fBpQ\fR perl-quotes the string. \fBdate +%FT%T\fR is the date in ISO8601 with time. .SS "EXAMPLE: Save output in ISO8601 dirs" .IX Subsection "EXAMPLE: Save output in ISO8601 dirs" Save output from \fBps aux\fR every second into dirs named yyyy\-mm\-ddThh:mm:ss+zz:zz. .PP .Vb 2 \& seq 1000 | parallel \-N0 \-j1 \-\-delay 1 \e \& \-\-results \*(Aq{= $_=\`date \-Isec\`; chomp=}/\*(Aq ps aux .Ve .SS "EXAMPLE: Digital clock with ""blinking"" :" .IX Subsection "EXAMPLE: Digital 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 modulo 2 is 1: Use ":" otherwise use " ": .PP .Vb 2 \& parallel \-k echo {1}\*(Aq{=3 $_=$_%2?":":" "=}\*(Aq{2}{3} \e \& ::: {0..12} ::: {0..5} ::: {0..9} .Ve .SS "EXAMPLE: Aggregating content of files" .IX Subsection "EXAMPLE: Aggregating content of files" This: .PP .Vb 2 \& parallel \-\-header : echo x{X}y{Y}z{Z} \e> x{X}y{Y}z{Z} \e \& ::: X {1..5} ::: Y {01..10} ::: Z {1..5} .Ve .PP will generate the files x1y01z1 .. x5y10z5. If you want to aggregate the output grouping on x and z you can do this: .PP .Vb 1 \& parallel eval \*(Aqcat {=s/y01/y*/=} > {=s/y01//=}\*(Aq ::: *y01* .Ve .PP For all values of x and z it runs commands like: .PP .Vb 1 \& cat x1y*z1 > x1z1 .Ve .PP So you end up with x1z1 .. x5z5 each containing the content of all values of y. .SS "EXAMPLE: Breadth first parallel web crawler/mirrorer" .IX Subsection "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. .PP Run like this: .PP .Vb 1 \& PARALLEL=\-j100 ./parallel\-crawl http://gatt.org.yeslab.org/ .Ve .PP Remove the \fBwget\fR part if you only want a web crawler. .PP 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. .PP .Vb 1 \& #!/bin/bash \& \& # E.g. http://gatt.org.yeslab.org/ \& URL=$1 \& # Stay inside the start dir \& BASEURL=$(echo $URL | perl \-pe \*(Aqs:#.*::; s:(//.*/)[^/]*:$1:\*(Aq) \& 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 {} \e; \e \& wget \-qm \-l1 \-Q1 {} \e; echo Spidered: {} \e>\e&2 | \& perl \-ne \*(Aqs/#.*//; s/\es+\ed+.\es(\eS+)$/$1/ and \& do { $seen{$1}++ or print }\*(Aq | \& grep \-F $BASEURL | \& grep \-v \-x \-F \-f $SEEN | tee \-a $SEEN > $URLLIST2 \& mv $URLLIST2 $URLLIST \& done \& \& rm \-f $URLLIST $URLLIST2 $SEEN .Ve .SS "EXAMPLE: Process files from a tar file while unpacking" .IX Subsection "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. .PP .Vb 2 \& tar xvf foo.tgz | perl \-ne \*(Aqprint $l;$l=$_;END{print $l}\*(Aq | \e \& parallel echo .Ve .PP The Perl one-liner is needed to make sure the file is complete before handing it to GNU \fBparallel\fR. .SS "EXAMPLE: Rewriting a for-loop and a while-read-loop" .IX Subsection "EXAMPLE: Rewriting a for-loop and a while-read-loop" for-loops like this: .PP .Vb 3 \& (for x in \`cat list\` ; do \& do_something $x \& done) | process_output .Ve .PP and while-read-loops like this: .PP .Vb 3 \& cat list | (while read x ; do \& do_something $x \& done) | process_output .Ve .PP can be written like this: .PP .Vb 1 \& cat list | parallel do_something | process_output .Ve .PP For example: Find which host name in a list has IP address 1.2.3 4: .PP .Vb 1 \& cat hosts.txt | parallel \-P 100 host | grep 1.2.3.4 .Ve .PP If the processing requires more steps the for-loop like this: .PP .Vb 5 \& (for x in \`cat list\` ; do \& no_extension=${x%.*}; \& do_step1 $x scale $no_extension.jpg \& do_step2 <$x $no_extension \& done) | process_output .Ve .PP and while-loops like this: .PP .Vb 5 \& cat list | (while read x ; do \& no_extension=${x%.*}; \& do_step1 $x scale $no_extension.jpg \& do_step2 <$x $no_extension \& done) | process_output .Ve .PP can be written like this: .PP .Vb 2 \& cat list | parallel "do_step1 {} scale {.}.jpg ; do_step2 <{} {.}" |\e \& process_output .Ve .PP If the body of the loop is bigger, it improves readability to use a function: .PP .Vb 4 \& (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 .Ve .PP can both be rewritten as: .PP .Vb 7 \& doit() { \& x=$1 \& do_something $x \& [... 100 lines that do something with $x ...] \& } \& export \-f doit \& cat list | parallel doit .Ve .SS "EXAMPLE: Rewriting nested for-loops" .IX Subsection "EXAMPLE: Rewriting nested for-loops" Nested for-loops like this: .PP .Vb 5 \& (for x in \`cat xlist\` ; do \& for y in \`cat ylist\` ; do \& do_something $x $y \& done \& done) | process_output .Ve .PP can be written like this: .PP .Vb 1 \& parallel do_something {1} {2} :::: xlist ylist | process_output .Ve .PP Nested for-loops like this: .PP .Vb 5 \& (for colour in red green blue ; do \& for size in S M L XL XXL ; do \& echo $colour $size \& done \& done) | sort .Ve .PP can be written like this: .PP .Vb 1 \& parallel echo {1} {2} ::: red green blue ::: S M L XL XXL | sort .Ve .SS "EXAMPLE: Finding the lowest difference between files" .IX Subsection "EXAMPLE: Finding the lowest difference between files" \&\fBdiff\fR is good for finding differences in text files. \fBdiff | wc \-l\fR gives an indication of the size of the difference. To find the differences between all files in the current dir do: .PP .Vb 1 \& parallel \-\-tag \*(Aqdiff {1} {2} | wc \-l\*(Aq ::: * ::: * | sort \-nk3 .Ve .PP This way it is possible to see if some files are closer to other files. .SS "EXAMPLE: for-loops with column names" .IX Subsection "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 \&\fB\-\-header :\fR to let the first argument be an named alias for the positional replacement string: .PP .Vb 2 \& parallel \-\-header : echo {colour} {size} \e \& ::: colour red green blue ::: size S M L XL XXL .Ve .PP This also works if the input file is a file with columns: .PP .Vb 2 \& cat addressbook.tsv | \e \& parallel \-\-colsep \*(Aq\et\*(Aq \-\-header : echo {Name} {E\-mail address} .Ve .SS "EXAMPLE: All combinations in a list" .IX Subsection "EXAMPLE: All combinations in a list" GNU \fBparallel\fR makes all combinations when given two lists. .PP To make all combinations in a single list with unique values, you repeat the list and use replacement string \fB{choose_k}\fR: .PP .Vb 1 \& parallel \-\-plus echo {choose_k} ::: A B C D ::: A B C D \& \& parallel \-\-plus echo 2{2choose_k} 1{1choose_k} ::: A B C D ::: A B C D .Ve .PP \&\fB{choose_k}\fR works for any number of input sources: .PP .Vb 1 \& parallel \-\-plus echo {choose_k} ::: A B C D ::: A B C D ::: A B C D .Ve .PP Where \fB{choose_k}\fR does not care about order, \fB{uniq}\fR cares about order. It simply skips jobs where values from different input sources are the same: .PP .Vb 3 \& parallel \-\-plus echo {uniq} ::: A B C ::: A B C ::: A B C \& parallel \-\-plus echo {1uniq}+{2uniq}+{3uniq} \e \& ::: A B C ::: A B C ::: A B C .Ve .PP The behaviour of \fB{choose_k}\fR is undefined, if the input values of each source are different. .SS "EXAMPLE: Which git branches are the most similar" .IX Subsection "EXAMPLE: Which git branches are the most similar" If you have a ton of branches in git, it may be useful to see how similar the branches are. This gives a rough estimate: .PP .Vb 3 \& parallel \-\-trim rl \-\-plus \-\-tag \*(Aqgit diff {choose_k} | wc \-c\*(Aq \e \& :::: <(git branch | grep \-v \*(Aq*\*(Aq) <(git branch | grep \-v \*(Aq*\*(Aq) | \& sort \-k3n .Ve .SS "EXAMPLE: From a to b and b to c" .IX Subsection "EXAMPLE: From a to b and b to c" Assume you have input like: .PP .Vb 5 \& aardvark \& babble \& cab \& dab \& each .Ve .PP and want to run combinations like: .PP .Vb 4 \& aardvark babble \& babble cab \& cab dab \& dab each .Ve .PP If the input is in the file in.txt: .PP .Vb 1 \& parallel echo {1} \- {2} ::::+ <(head \-n \-1 in.txt) <(tail \-n +2 in.txt) .Ve .PP If the input is in the array \f(CW$a\fR here are two solutions: .PP .Vb 3 \& seq $((${#a[@]}\-1)) | \e \& env_parallel \-\-env a echo \*(Aq${a[{=$_\-\-=}]} \- ${a[{}]}\*(Aq \& parallel echo {1} \- {2} ::: "${a[@]::${#a[@]}\-1}" :::+ "${a[@]:1}" .Ve .SS "EXAMPLE: Count the differences between all files in a dir" .IX Subsection "EXAMPLE: Count the differences between all files in a dir" Using \fB\-\-results\fR the results are saved in /tmp/diffcount*. .PP .Vb 2 \& parallel \-\-results /tmp/diffcount "diff \-U 0 {1} {2} | \e \& tail \-n +3 |grep \-v \*(Aq^@\*(Aq|wc \-l" ::: * ::: * .Ve .PP To see the difference between file A and file B look at the file \&'/tmp/diffcount/1/A/2/B'. .SS "EXAMPLE: Speeding up fast jobs" .IX Subsection "EXAMPLE: Speeding up fast jobs" Starting a job on the local machine takes around 3\-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 \fB\-X\fR which will make the overhead less significant. Compare the speed of these: .PP .Vb 2 \& seq \-w 0 9999 | parallel touch pict{}.jpg \& seq \-w 0 9999 | parallel \-X touch pict{}.jpg .Ve .PP If your program cannot take multiple arguments, then you can use GNU \&\fBparallel\fR to spawn multiple GNU \fBparallel\fRs: .PP .Vb 2 \& seq \-w 0 9999999 | \e \& parallel \-j10 \-q \-I,, \-\-pipe parallel \-j0 touch pict{}.jpg .Ve .PP If \fB\-j0\fR 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. .PP If you do not need GNU \fBparallel\fR to have control over each job (so no need for \fB\-\-retries\fR or \fB\-\-joblog\fR or similar), then it can be even faster if you can generate the command lines and pipe those to a shell. So if you can do this: .PP .Vb 1 \& mygenerator | sh .Ve .PP Then that can be parallelized like this: .PP .Vb 1 \& mygenerator | parallel \-\-pipe \-\-block 10M sh .Ve .PP E.g. .PP .Vb 4 \& mygenerator() { \& seq 10000000 | perl \-pe \*(Aqprint "echo This is fast job number "\*(Aq; \& } \& mygenerator | parallel \-\-pipe \-\-block 10M sh .Ve .PP The overhead is 100000 times smaller namely around 100 nanoseconds per job. .SS "EXAMPLE: Using shell variables" .IX Subsection "EXAMPLE: Using shell variables" When using shell variables you need to quote them correctly as they may otherwise be interpreted by the shell. .PP Notice the difference between: .PP .Vb 2 \& ARR=("My brother\*(Aqs 12\e" records are worth <\e$\e$\e$>"\*(Aq!\*(Aq Foo Bar) \& parallel echo ::: ${ARR[@]} # This is probably not what you want .Ve .PP and: .PP .Vb 2 \& ARR=("My brother\*(Aqs 12\e" records are worth <\e$\e$\e$>"\*(Aq!\*(Aq Foo Bar) \& parallel echo ::: "${ARR[@]}" .Ve .PP When using variables in the actual command that contains special characters (e.g. space) you can quote them using \fB'"$VAR"'\fR or using "'s and \fB\-q\fR: .PP .Vb 4 \& VAR="My brother\*(Aqs 12\e" records are worth <\e$\e$\e$>" \& parallel \-q echo "$VAR" ::: \*(Aq!\*(Aq \& export VAR \& parallel echo \*(Aq"$VAR"\*(Aq ::: \*(Aq!\*(Aq .Ve .PP If \fR\f(CB$VAR\fR\fB\fR does not contain ' then \fB"'$VAR'"\fR will also work (and does not need \fBexport\fR): .PP .Vb 2 \& VAR="My 12\e" records are worth <\e$\e$\e$>" \& parallel echo "\*(Aq$VAR\*(Aq" ::: \*(Aq!\*(Aq .Ve .PP If you use them in a function you just quote as you normally would do: .PP .Vb 5 \& VAR="My brother\*(Aqs 12\e" records are worth <\e$\e$\e$>" \& export VAR \& myfunc() { echo "$VAR" "$1"; } \& export \-f myfunc \& parallel myfunc ::: \*(Aq!\*(Aq .Ve .SS "EXAMPLE: Group output lines" .IX Subsection "EXAMPLE: Group output lines" When running jobs that output data, you often do not want the output of multiple jobs to run together. GNU \fBparallel\fR 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 \fB\-\-line\-buffer\fR. If you want output to be printed as soon as possible you can use \fB\-u\fR. .PP Compare the output of: .PP .Vb 12 \& parallel wget \-\-progress=dot \-\-limit\-rate=100k \e \& https://ftpmirror.gnu.org/parallel/parallel\-20{}0822.tar.bz2 \e \& ::: {12..16} \& parallel \-\-line\-buffer wget \-\-progress=dot \-\-limit\-rate=100k \e \& https://ftpmirror.gnu.org/parallel/parallel\-20{}0822.tar.bz2 \e \& ::: {12..16} \& parallel \-\-latest\-line wget \-\-progress=dot \-\-limit\-rate=100k \e \& https://ftpmirror.gnu.org/parallel/parallel\-20{}0822.tar.bz2 \e \& ::: {12..16} \& parallel \-u wget \-\-progress=dot \-\-limit\-rate=100k \e \& https://ftpmirror.gnu.org/parallel/parallel\-20{}0822.tar.bz2 \e \& ::: {12..16} .Ve .SS "EXAMPLE: Tag output lines" .IX Subsection "EXAMPLE: Tag output lines" GNU \fBparallel\fR groups the output lines, but it can be hard to see where the different jobs begin. \fB\-\-tag\fR prepends the argument to make that more visible: .PP .Vb 3 \& parallel \-\-tag wget \-\-limit\-rate=100k \e \& https://ftpmirror.gnu.org/parallel/parallel\-20{}0822.tar.bz2 \e \& ::: {12..16} .Ve .PP \&\fB\-\-tag\fR works with \fB\-\-line\-buffer\fR but not with \fB\-u\fR: .PP .Vb 3 \& parallel \-\-tag \-\-line\-buffer wget \-\-limit\-rate=100k \e \& https://ftpmirror.gnu.org/parallel/parallel\-20{}0822.tar.bz2 \e \& ::: {12..16} .Ve .PP Check the uptime of the servers in \fI~/.parallel/sshloginfile\fR: .PP .Vb 1 \& parallel \-\-tag \-S .. \-\-nonall uptime .Ve .SS "EXAMPLE: Colorize output" .IX Subsection "EXAMPLE: Colorize output" Give each job a new color. Most terminals support ANSI colors with the escape code "\e033[30;3Xm" where 0 <= X <= 7: .PP .Vb 4 \& seq 10 | \e \& parallel \-\-tagstring \*(Aq\e033[30;3{=$_=++$::color%8=}m\*(Aq seq {} \& parallel \-\-rpl \*(Aq{color} $_="\e033[30;3".(++$::color%8)."m"\*(Aq \e \& \-\-tagstring {color} seq {} ::: {1..10} .Ve .PP To get rid of the initial \et (which comes from \fB\-\-tagstring\fR): .PP .Vb 1 \& ... | perl \-pe \*(Aqs/\et//\*(Aq .Ve .SS "EXAMPLE: Keep order of output same as order of input" .IX Subsection "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. \fB\-k\fR will make sure the order of output will be in the same order as input even if later jobs end before earlier jobs. .PP Append a string to every line in a text file: .PP .Vb 1 \& cat textfile | parallel \-k echo {} append_string .Ve .PP If you remove \fB\-k\fR some of the lines may come out in the wrong order. .PP Another example is \fBtraceroute\fR: .PP .Vb 1 \& parallel traceroute ::: qubes\-os.org debian.org freenetproject.org .Ve .PP will give traceroute of qubes\-os.org, debian.org and freenetproject.org, but it will be sorted according to which job completed first. .PP To keep the order the same as input run: .PP .Vb 1 \& parallel \-k traceroute ::: qubes\-os.org debian.org freenetproject.org .Ve .PP This will make sure the traceroute to qubes\-os.org will be printed first. .PP 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. .PP To download byte 10000000\-19999999 you can use \fBcurl\fR: .PP .Vb 1 \& curl \-r 10000000\-19999999 https://example.com/the/big/file >file.part .Ve .PP To download a 1 GB file we need 100 10MB chunks downloaded and combined in the correct order. .PP .Vb 2 \& seq 0 99 | parallel \-k curl \-r \e \& {}0000000\-{}9999999 https://example.com/the/big/file > file .Ve .SS "EXAMPLE: Parallel grep" .IX Subsection "EXAMPLE: Parallel grep" \&\fBgrep \-r\fR greps recursively through directories. GNU \fBparallel\fR can often speed this up. .PP .Vb 1 \& find . \-type f | parallel \-k \-j150% \-n 1000 \-m grep \-H \-n STRING {} .Ve .PP This will run 1.5 job per CPU, and give 1000 arguments to \fBgrep\fR. .PP There are situations where the above will be slower than \fBgrep \-r\fR: .IP \(bu 2 If data is already in RAM. The overhead of starting jobs and buffering output may outweigh the benefit of running in parallel. .IP \(bu 2 If the files are big. If a file cannot be read in a single seek, the disk may start thrashing. .PP The speedup is caused by two factors: .IP \(bu 2 On rotating harddisks small files often require a seek for each file. By searching for more files in parallel, the arm may pass another wanted file on its way. .IP \(bu 2 NVMe drives often perform better by having multiple command running in parallel. .SS "EXAMPLE: Grepping n lines for m regular expressions." .IX Subsection "EXAMPLE: Grepping n lines for m regular expressions." The simplest solution to grep a big file for a lot of regexps is: .PP .Vb 1 \& grep \-f regexps.txt bigfile .Ve .PP Or if the regexps are fixed strings: .PP .Vb 1 \& grep \-F \-f regexps.txt bigfile .Ve .PP There are 3 limiting factors: CPU, RAM, and disk I/O. .PP RAM is easy to measure: If the \fBgrep\fR process takes up most of your free memory (e.g. when running \fBtop\fR), then RAM is a limiting factor. .PP CPU is also easy to measure: If the \fBgrep\fR takes >90% CPU in \fBtop\fR, then the CPU is a limiting factor, and parallelization will speed this up. .PP 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. .PP \fILimiting factor: RAM\fR .IX Subsection "Limiting factor: RAM" .PP The normal \fBgrep \-f regexps.txt bigfile\fR 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. .PP \&\fBgrep \-F\fR takes around 100 bytes of RAM and \fBgrep\fR 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. .PP 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: .PP .Vb 2 \& ID1 foo bar baz Identifier1 quux \& fubar ID2 foo bar baz Identifier2 .Ve .PP then your regexps.txt can be converted from: .PP .Vb 2 \& ID1.*Identifier1 \& ID2.*Identifier2 .Ve .PP into: .PP .Vb 2 \& ID1 foo bar baz Identifier1 \& ID2 foo bar baz Identifier2 .Ve .PP This way you can use \fBgrep \-F\fR which takes around 80% less memory and is much faster. .PP If it still does not fit in memory you can do this: .PP .Vb 2 \& parallel \-\-pipe\-part \-a regexps.txt \-\-block 1M grep \-F \-f \- \-n bigfile | \e \& sort \-un | perl \-pe \*(Aqs/^\ed+://\*(Aq .Ve .PP The 1M should be your free memory divided by the number of CPU threads and divided by 200 for \fBgrep \-F\fR and by 1000 for normal \fBgrep\fR. On GNU/Linux you can do: .PP .Vb 3 \& free=$(awk \*(Aq/^((Swap)?Cached|MemFree|Buffers):/ { sum += $2 } \& END { print sum }\*(Aq /proc/meminfo) \& percpu=$((free / 200 / $(parallel \-\-number\-of\-threads)))k \& \& parallel \-\-pipe\-part \-a regexps.txt \-\-block $percpu \-\-compress \e \& grep \-F \-f \- \-n bigfile | \e \& sort \-un | perl \-pe \*(Aqs/^\ed+://\*(Aq .Ve .PP If you can live with duplicated lines and wrong order, it is faster to do: .PP .Vb 2 \& parallel \-\-pipe\-part \-a regexps.txt \-\-block $percpu \-\-compress \e \& grep \-F \-f \- bigfile .Ve .PP \fILimiting factor: CPU\fR .IX Subsection "Limiting factor: CPU" .PP If the CPU is the limiting factor parallelization should be done on the regexps: .PP .Vb 3 \& cat regexps.txt | parallel \-\-pipe \-L1000 \-\-round\-robin \-\-compress \e \& grep \-f \- \-n bigfile | \e \& sort \-un | perl \-pe \*(Aqs/^\ed+://\*(Aq .Ve .PP The command will start one \fBgrep\fR per CPU and read \fIbigfile\fR 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 \fIregexps.txt\fR it may be faster to use \fB\-\-block 10m\fR instead of \fB\-L1000\fR. .PP 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 \fIbigfile\fR: .PP .Vb 2 \& parallel \-\-pipe\-part \-\-block 100M \-a bigfile \-k \-\-compress \e \& grep \-f regexps.txt .Ve .PP This will split \fIbigfile\fR into 100MB chunks and run \fBgrep\fR on each of these chunks. To parallelize both reading of \fIbigfile\fR and \fIregexps.txt\fR combine the two using \fB\-\-cat\fR: .PP .Vb 2 \& parallel \-\-pipe\-part \-\-block 100M \-a bigfile \-\-cat cat regexps.txt \e \& \e| parallel \-\-pipe \-L1000 \-\-round\-robin grep \-f \- {} .Ve .PP If a line matches multiple regexps, the line may be duplicated. .PP \fIBigger problem\fR .IX Subsection "Bigger problem" .PP If the problem is too big to be solved by this, you are probably ready for Lucene. .SS "EXAMPLE: Using remote computers" .IX Subsection "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 \&\fBssh-copy-id\fR, \fBssh-agent\fR, and \fBsshpass\fR may help you do that). .PP 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: .PP .Vb 10 \& # 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 \*(AqHost *\*(Aq; echo StrictHostKeyChecking no) >> .ssh/config \& parallel \-\-slf my_cluster \-\-nonall true \& # Remove the disabling of StrictHostKeyChecking \& mv .ssh/config.backup .ssh/config .Ve .PP The servers in \fB.parallel/my_cluster\fR are now added in \fB.ssh/known_hosts\fR. .PP To run \fBecho\fR on \fBserver.example.com\fR: .PP .Vb 1 \& seq 10 | parallel \-\-sshlogin server.example.com echo .Ve .PP To run commands on more than one remote computer run: .PP .Vb 1 \& seq 10 | parallel \-\-sshlogin s1.example.com,s2.example.net echo .Ve .PP Or: .PP .Vb 2 \& seq 10 | parallel \-\-sshlogin server.example.com \e \& \-\-sshlogin server2.example.net echo .Ve .PP If the login username is \fIfoo\fR on \fIserver2.example.net\fR use: .PP .Vb 2 \& seq 10 | parallel \-\-sshlogin server.example.com \e \& \-\-sshlogin foo@server2.example.net echo .Ve .PP If your list of hosts is \fIserver1\-88.example.net\fR with login \fIfoo\fR: .PP .Vb 1 \& seq 10 | parallel \-Sfoo@server{1..88}.example.net echo .Ve .PP To distribute the commands to a list of computers, make a file \&\fImycomputers\fR with all the computers: .PP .Vb 3 \& server.example.com \& foo@server2.example.com \& server3.example.com .Ve .PP Then run: .PP .Vb 1 \& seq 10 | parallel \-\-sshloginfile mycomputers echo .Ve .PP To include the local computer add the special sshlogin ':' to the list: .PP .Vb 4 \& server.example.com \& foo@server2.example.com \& server3.example.com \& : .Ve .PP GNU \fBparallel\fR will try to determine the number of CPUs on each of the remote computers, and run one job per CPU \- even if the remote computers do not have the same number of CPUs. .PP If the number of CPUs on the remote computers is not identified correctly the number of CPUs can be added in front. Here the computer has 8 CPUs. .PP .Vb 1 \& seq 10 | parallel \-\-sshlogin 8/server.example.com echo .Ve .SS "EXAMPLE: Transferring of files" .IX Subsection "EXAMPLE: Transferring of files" To recompress gzipped files with \fBbzip2\fR using a remote computer run: .PP .Vb 3 \& find logs/ \-name \*(Aq*.gz\*(Aq | \e \& parallel \-\-sshlogin server.example.com \e \& \-\-transfer "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .PP This will list the .gz\-files in the \fIlogs\fR directory and all directories below. Then it will transfer the files to \&\fIserver.example.com\fR to the corresponding directory in \&\fR\f(CI$HOME\fR\fI/logs\fR. On \fIserver.example.com\fR the file will be recompressed using \fBzcat\fR and \fBbzip2\fR resulting in the corresponding file with \&\fI.gz\fR replaced with \fI.bz2\fR. .PP If you want the resulting bz2\-file to be transferred back to the local computer add \fI\-\-return {.}.bz2\fR: .PP .Vb 3 \& find logs/ \-name \*(Aq*.gz\*(Aq | \e \& parallel \-\-sshlogin server.example.com \e \& \-\-transfer \-\-return {.}.bz2 "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .PP After the recompressing is done the \fI.bz2\fR\-file is transferred back to the local computer and put next to the original \fI.gz\fR\-file. .PP If you want to delete the transferred files on the remote computer add \&\fI\-\-cleanup\fR. This will remove both the file transferred to the remote computer and the files transferred from the remote computer: .PP .Vb 3 \& find logs/ \-name \*(Aq*.gz\*(Aq | \e \& parallel \-\-sshlogin server.example.com \e \& \-\-transfer \-\-return {.}.bz2 \-\-cleanup "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .PP If you want run on several computers add the computers to \fI\-\-sshlogin\fR either using ',' or multiple \fI\-\-sshlogin\fR: .PP .Vb 4 \& find logs/ \-name \*(Aq*.gz\*(Aq | \e \& parallel \-\-sshlogin server.example.com,server2.example.com \e \& \-\-sshlogin server3.example.com \e \& \-\-transfer \-\-return {.}.bz2 \-\-cleanup "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .PP You can add the local computer using \fI\-\-sshlogin :\fR. This will disable the removing and transferring for the local computer only: .PP .Vb 5 \& find logs/ \-name \*(Aq*.gz\*(Aq | \e \& parallel \-\-sshlogin server.example.com,server2.example.com \e \& \-\-sshlogin server3.example.com \e \& \-\-sshlogin : \e \& \-\-transfer \-\-return {.}.bz2 \-\-cleanup "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .PP Often \fI\-\-transfer\fR, \fI\-\-return\fR and \fI\-\-cleanup\fR are used together. They can be shortened to \fI\-\-trc\fR: .PP .Vb 5 \& find logs/ \-name \*(Aq*.gz\*(Aq | \e \& parallel \-\-sshlogin server.example.com,server2.example.com \e \& \-\-sshlogin server3.example.com \e \& \-\-sshlogin : \e \& \-\-trc {.}.bz2 "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .PP With the file \fImycomputers\fR containing the list of computers it becomes: .PP .Vb 2 \& find logs/ \-name \*(Aq*.gz\*(Aq | parallel \-\-sshloginfile mycomputers \e \& \-\-trc {.}.bz2 "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .PP If the file \fI~/.parallel/sshloginfile\fR contains the list of computers the special short hand \fI\-S ..\fR can be used: .PP .Vb 2 \& find logs/ \-name \*(Aq*.gz\*(Aq | parallel \-S .. \e \& \-\-trc {.}.bz2 "zcat {} | bzip2 \-9 >{.}.bz2" .Ve .SS "EXAMPLE: Advanced file transfer" .IX Subsection "EXAMPLE: Advanced file transfer" Assume you have files in in/*, want them processed on server, and transferred back into /other/dir: .PP .Vb 2 \& parallel \-S server \-\-trc /other/dir/./{/}.out \e \& cp {/} {/}.out ::: in/./* .Ve .SS "EXAMPLE: Distributing work to local and remote computers" .IX Subsection "EXAMPLE: Distributing work to local and remote computers" Convert *.mp3 to *.ogg running one process per CPU on local computer and server2: .PP .Vb 2 \& parallel \-\-trc {.}.ogg \-S server2,: \e \& \*(Aqmpg321 \-w \- {} | oggenc \-q0 \- \-o {.}.ogg\*(Aq ::: *.mp3 .Ve .SS "EXAMPLE: Running the same command on remote computers" .IX Subsection "EXAMPLE: Running the same command on remote computers" To run the command \fBuptime\fR on remote computers you can do: .PP .Vb 1 \& parallel \-\-tag \-\-nonall \-S server1,server2 uptime .Ve .PP \&\fB\-\-nonall\fR reads no arguments. If you have a list of jobs you want to run on each computer you can do: .PP .Vb 1 \& parallel \-\-tag \-\-onall \-S server1,server2 echo ::: 1 2 3 .Ve .PP Remove \fB\-\-tag\fR if you do not want the sshlogin added before the output. .PP If you have a lot of hosts use '\-j0' to access more hosts in parallel. .SS "EXAMPLE: Running 'sudo' on remote computers" .IX Subsection "EXAMPLE: Running 'sudo' on remote computers" Put the password into passwordfile then run: .PP .Vb 2 \& parallel \-\-ssh \*(Aqcat passwordfile | ssh\*(Aq \-\-nonall \e \& \-S user@server1,user@server2 sudo \-S ls \-l /root .Ve .SS "EXAMPLE: Using remote computers behind NAT wall" .IX Subsection "EXAMPLE: Using remote computers behind NAT wall" If the workers are behind a NAT wall, you need some trickery to get to them. .PP If you can \fBssh\fR to a jumphost, and reach the workers from there, then the obvious solution would be this, but it \fBdoes not work\fR: .PP .Vb 1 \& parallel \-\-ssh \*(Aqssh jumphost ssh\*(Aq \-S host1 echo ::: DOES NOT WORK .Ve .PP It does not work because the command is dequoted by \fBssh\fR twice where as GNU \fBparallel\fR only expects it to be dequoted once. .PP You can use a bash function and have GNU \fBparallel\fR quote the command: .PP .Vb 3 \& jumpssh() { ssh \-A jumphost ssh $(parallel \-\-shellquote ::: "$@"); } \& export \-f jumpssh \& parallel \-\-ssh jumpssh \-S host1 echo ::: this works .Ve .PP Or you can instead put this in \fB~/.ssh/config\fR: .PP .Vb 2 \& Host host1 host2 host3 \& ProxyCommand ssh jumphost.domain nc \-w 1 %h 22 .Ve .PP It requires \fBnc(netcat)\fR to be installed on jumphost. With this you can simply: .PP .Vb 1 \& parallel \-S host1,host2,host3 echo ::: This does work .Ve .PP \fINo jumphost, but port forwards\fR .IX Subsection "No jumphost, but port forwards" .PP 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 \fB~/.ssh/config\fR: .PP .Vb 8 \& Host host1.v \& Port 22001 \& Host host2.v \& Port 22002 \& Host host3.v \& Port 22003 \& Host *.v \& Hostname firewall .Ve .PP And then use host{1..3}.v as normal hosts: .PP .Vb 1 \& parallel \-S host1.v,host2.v,host3.v echo ::: a b c .Ve .PP \fINo jumphost, no port forwards\fR .IX Subsection "No jumphost, no port forwards" .PP 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. .PP You need to install TOR and setup a hidden service. In \fBtorrc\fR put: .PP .Vb 2 \& HiddenServiceDir /var/lib/tor/hidden_service/ \& HiddenServicePort 22 127.0.0.1:22 .Ve .PP Then start TOR: \fB/etc/init.d/tor restart\fR .PP The TOR hostname is now in \fB/var/lib/tor/hidden_service/hostname\fR and is something similar to \fBizjafdceobowklhz.onion\fR. Now you simply prepend \fBtorsocks\fR to \fBssh\fR: .PP .Vb 2 \& parallel \-\-ssh \*(Aqtorsocks ssh\*(Aq \-S izjafdceobowklhz.onion \e \& \-S zfcdaeiojoklbwhz.onion,auclucjzobowklhi.onion echo ::: a b c .Ve .PP If not all hosts are accessible through TOR: .PP .Vb 2 \& parallel \-S \*(Aqtorsocks ssh izjafdceobowklhz.onion,host2,host3\*(Aq \e \& echo ::: a b c .Ve .PP See more \fBssh\fR tricks on https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Proxies_and_Jump_Hosts .SS "EXAMPLE: Use sshpass with ssh" .IX Subsection "EXAMPLE: Use sshpass with ssh" If you cannot use passwordless login, you may be able to use \fBsshpass\fR: .PP .Vb 1 \& seq 10 | parallel \-S user\-with\-password:MyPassword@server echo .Ve .PP or: .PP .Vb 2 \& export SSHPASS=\*(AqMyPa$$w0rd\*(Aq \& seq 10 | parallel \-S user\-with\-password:@server echo .Ve .SS "EXAMPLE: Use outrun instead of ssh" .IX Subsection "EXAMPLE: Use outrun instead of ssh" \&\fBoutrun\fR lets you run a command on a remote server. \fBoutrun\fR sets up a connection to access files at the source server, and automatically transfers files. \fBoutrun\fR must be installed on the remote system. .PP You can use \fBoutrun\fR in an sshlogin this way: .PP .Vb 1 \& parallel \-S \*(Aqoutrun user@server\*(Aq command .Ve .PP or: .PP .Vb 1 \& parallel \-\-ssh outrun \-S server command .Ve .SS "EXAMPLE: Slurm cluster" .IX Subsection "EXAMPLE: Slurm cluster" The Slurm Workload Manager is used in many clusters. .PP Here is a simple example of using GNU \fBparallel\fR to call \fBsrun\fR: .PP .Vb 1 \& #!/bin/bash \& \& #SBATCH \-\-time 00:02:00 \& #SBATCH \-\-ntasks=4 \& #SBATCH \-\-job\-name GnuParallelDemo \& #SBATCH \-\-output gnuparallel.out \& \& module purge \& module load gnu_parallel \& \& my_parallel="parallel \-\-delay .2 \-j $SLURM_NTASKS" \& my_srun="srun \-\-export=all \-\-exclusive \-n1" \& my_srun="$my_srun \-\-cpus\-per\-task=1 \-\-cpu\-bind=cores" \& $my_parallel "$my_srun" echo This is job {} ::: {1..20} .Ve .SS "EXAMPLE: Parallelizing rsync" .IX Subsection "EXAMPLE: Parallelizing rsync" \&\fBrsync\fR is a great tool, but sometimes it will not fill up the available bandwidth. Running multiple \fBrsync\fR in parallel can fix this. .PP .Vb 3 \& cd src\-dir \& find . \-type f | \& parallel \-j10 \-X rsync \-zR \-Ha ./{} fooserver:/dest\-dir/ .Ve .PP Adjust \fB\-j10\fR until you find the optimal number. .PP \&\fBrsync \-R\fR will create the needed subdirectories, so all files are not put into a single dir. The \fB./\fR is needed so the resulting command looks similar to: .PP .Vb 1 \& rsync \-zR ././sub/dir/file fooserver:/dest\-dir/ .Ve .PP The \fB/./\fR is what \fBrsync \-R\fR works on. .PP 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: .PP .Vb 1 \& seq \-w 0 99 | parallel rsync \-Havessh fooserver:src/*{}.png destdir/ .Ve .SS "EXAMPLE: Use multiple inputs in one command" .IX Subsection "EXAMPLE: Use multiple inputs in one command" Copy files like foo.es.ext to foo.ext: .PP .Vb 1 \& ls *.es.* | perl \-pe \*(Aqprint; s/\e.es//\*(Aq | parallel \-N2 cp {1} {2} .Ve .PP The perl command spits out 2 lines for each input. GNU \fBparallel\fR takes 2 inputs (using \fB\-N2\fR) and replaces {1} and {2} with the inputs. .PP Count in binary: .PP .Vb 1 \& parallel \-k echo ::: 0 1 ::: 0 1 ::: 0 1 ::: 0 1 ::: 0 1 ::: 0 1 .Ve .PP Print the number on the opposing sides of a six sided die: .PP .Vb 2 \& parallel \-\-link \-a <(seq 6) \-a <(seq 6 \-1 1) echo \& parallel \-\-link echo :::: <(seq 6) <(seq 6 \-1 1) .Ve .PP Convert files from all subdirs to PNG-files with consecutive numbers (useful for making input PNG's for \fBffmpeg\fR): .PP .Vb 2 \& parallel \-\-link \-a <(find . \-type f | sort) \e \& \-a <(seq $(find . \-type f|wc \-l)) convert {1} {2}.png .Ve .PP Alternative version: .PP .Vb 1 \& find . \-type f | sort | parallel convert {} {#}.png .Ve .SS "EXAMPLE: Use a table as input" .IX Subsection "EXAMPLE: Use a table as input" Content of table_file.tsv: .PP .Vb 2 \& foobar \& baz quux .Ve .PP To run: .PP .Vb 2 \& cmd \-o bar \-i foo \& cmd \-o quux \-i baz .Ve .PP you can run: .PP .Vb 1 \& parallel \-a table_file.tsv \-\-colsep \*(Aq\et\*(Aq cmd \-o {2} \-i {1} .Ve .PP Note: The default for GNU \fBparallel\fR is to remove the spaces around the columns. To keep the spaces: .PP .Vb 1 \& parallel \-a table_file.tsv \-\-trim n \-\-colsep \*(Aq\et\*(Aq cmd \-o {2} \-i {1} .Ve .SS "EXAMPLE: Output to database" .IX Subsection "EXAMPLE: Output to database" GNU \fBparallel\fR can output to a database table and a CSV-file: .PP .Vb 3 \& dburl=csv:///%2Ftmp%2Fmydir \& dbtableurl=$dburl/mytable.csv \& parallel \-\-sqlandworker $dbtableurl seq ::: {1..10} .Ve .PP It is rather slow and takes up a lot of CPU time because GNU \&\fBparallel\fR parses the whole CSV file for each update. .PP A better approach is to use an SQLite-base and then convert that to CSV: .PP .Vb 4 \& dburl=sqlite3:///%2Ftmp%2Fmy.sqlite \& dbtableurl=$dburl/mytable \& parallel \-\-sqlandworker $dbtableurl seq ::: {1..10} \& sql $dburl \*(Aq.headers on\*(Aq \*(Aq.mode csv\*(Aq \*(AqSELECT * FROM mytable;\*(Aq .Ve .PP This takes around a second per job. .PP If you have access to a real database system, such as PostgreSQL, it is even faster: .PP .Vb 5 \& dburl=pg://user:pass@host/mydb \& dbtableurl=$dburl/mytable \& parallel \-\-sqlandworker $dbtableurl seq ::: {1..10} \& sql $dburl \e \& "COPY (SELECT * FROM mytable) TO stdout DELIMITER \*(Aq,\*(Aq CSV HEADER;" .Ve .PP Or MySQL: .PP .Vb 7 \& 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 \*(Aqs/"/""/g; s/\et/","/g; s/^/"/; s/$/"/; \& %s=("\e\e" => "\e\e", "t" => "\et", "n" => "\en"); \& s/\e\e([\e\etn])/$s{$1}/g;\*(Aq mytable.tsv .Ve .SS "EXAMPLE: Output to CSV-file for R" .IX Subsection "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 \fB\-\-results\fR: .PP .Vb 5 \& parallel \-\-results my.csv seq ::: 10 20 30 \& R \& > mydf <\- read.csv("my.csv"); \& > print(mydf[2,]) \& > write(as.character(mydf[2,c("Stdout")]),\*(Aq\*(Aq) .Ve .SS "EXAMPLE: Use XML as input" .IX Subsection "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 .PP Using \fBxpath\fR you can extract the URLs for 2019 and download them using GNU \fBparallel\fR: .PP .Vb 3 \& wget \-O \- http://arkiv.radio24syv.dk/audiopodcast/channel/4466232 | \e \& xpath \-e "//pubDate[contains(text(),\*(Aq2019\*(Aq)]/../enclosure/@url" | \e \& parallel \-u wget \*(Aq{= s/ url="//; s/"//; =}\*(Aq .Ve .SS "EXAMPLE: Run the same command 10 times" .IX Subsection "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: .PP .Vb 1 \& seq 10 | parallel \-n0 my_command my_args .Ve .SS "EXAMPLE: Working as cat | sh. Resource inexpensive jobs and evaluation" .IX Subsection "EXAMPLE: Working as cat | sh. Resource inexpensive jobs and evaluation" GNU \fBparallel\fR can work similar to \fBcat | sh\fR. .PP 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. .PP The content of the file jobs_to_run: .PP .Vb 7 \& 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 .Ve .PP To run 100 processes simultaneously do: .PP .Vb 1 \& parallel \-j 100 < jobs_to_run .Ve .PP As there is not a \fIcommand\fR the jobs will be evaluated by the shell. .SS "EXAMPLE: Call program with FASTA sequence" .IX Subsection "EXAMPLE: Call program with FASTA sequence" FASTA files have the format: .PP .Vb 7 \& >Sequence name1 \& sequence \& sequence continued \& >Sequence name2 \& sequence \& sequence continued \& more sequence .Ve .PP To call \fBmyprog\fR with the sequence as argument run: .PP .Vb 3 \& cat file.fasta | \& parallel \-\-pipe \-N1 \-\-recstart \*(Aq>\*(Aq \-\-rrs \e \& \*(Aqread a; echo Name: "$a"; myprog $(tr \-d "\en")\*(Aq .Ve .SS "EXAMPLE: Call program with interleaved FASTQ records" .IX Subsection "EXAMPLE: Call program with interleaved FASTQ records" FASTQ files have the format: .PP .Vb 4 \& @M10991:61:000000000\-A7EML:1:1101:14011:1001 1:N:0:28 \& CTCCTAGGTCGGCATGATGGGGGAAGGAGAGCATGGGAAGAAATGAGAGAGTAGCAAGG \& + \& #8BCCGGGGGFEFECFGGGGGGGGG@;FFGGGEG@FF bigfile.gz .Ve .PP This will split \fBbigfile\fR into blocks of 1 MB and pass that to \fBgzip \&\-9\fR in parallel. One \fBgzip\fR will be run per CPU. The output of \fBgzip \&\-9\fR will be kept in order and saved to \fBbigfile.gz\fR .PP \&\fBgzip\fR works fine if the output is appended, but some processing does not work like that \- for example sorting. For this GNU \fBparallel\fR can put the output of each command into a file. This will sort a big file in parallel: .PP .Vb 2 \& cat bigfile | parallel \-\-pipe \-\-files sort |\e \& parallel \-Xj1 sort \-m {} \*(Aq;\*(Aq rm {} >bigfile.sort .Ve .PP Here \fBbigfile\fR is split into blocks of around 1MB, each block ending in '\en' (which is the default for \fB\-\-recend\fR). Each block is passed to \fBsort\fR and the output from \fBsort\fR is saved into files. These files are passed to the second \fBparallel\fR that runs \fBsort \-m\fR on the files before it removes the files. The output is saved to \&\fBbigfile.sort\fR. .PP GNU \fBparallel\fR's \fB\-\-pipe\fR maxes out at around 100 MB/s because every byte has to be copied through GNU \fBparallel\fR. But if \fBbigfile\fR is a real (seekable) file GNU \fBparallel\fR can by-pass the copying and send the parts directly to the program: .PP .Vb 2 \& parallel \-\-pipe\-part \-\-block 100m \-a bigfile \-\-files sort |\e \& parallel \-Xj1 sort \-m {} \*(Aq;\*(Aq rm {} >bigfile.sort .Ve .SS "EXAMPLE: Grouping input lines" .IX Subsection "EXAMPLE: Grouping input lines" When processing with \fB\-\-pipe\fR you may have lines grouped by a value. Here is \fImy.csv\fR: .PP .Vb 10 \& 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 .Ve .PP Let us assume you want GNU \fBparallel\fR to process each customer. In other words: You want all the transactions for a single customer to be treated as a single record. .PP To do this we preprocess the data with a program that inserts a record separator before each customer (column 2 = \f(CW$F\fR[1]). Here we first make a 50 character random string, which we then use as the separator: .PP .Vb 4 \& sep=\`perl \-e \*(Aqprint map { ("a".."z","A".."Z")[rand(52)] } (1..50);\*(Aq\` \& cat my.csv | \e \& perl \-ape \*(Aq$F[1] ne $l and print "\*(Aq$sep\*(Aq"; $l = $F[1]\*(Aq | \e \& parallel \-\-recend $sep \-\-rrs \-\-pipe \-N1 wc .Ve .PP If your program can process multiple customers replace \fB\-N1\fR with a reasonable \fB\-\-blocksize\fR. .SS "EXAMPLE: Running more than 250 jobs workaround" .IX Subsection "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 \fBparallel\fRs then each of them can run 250 jobs. This will spawn up to 2500 jobs: .PP .Vb 2 \& cat myinput |\e \& parallel \-\-pipe \-N 50 \-\-round\-robin \-j50 parallel \-j50 your_prg .Ve .PP 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): .PP .Vb 2 \& cat myinput |\e \& parallel \-\-pipe \-N 250 \-\-round\-robin \-j250 parallel \-j250 your_prg .Ve .SS "EXAMPLE: Working as mutex and counting semaphore" .IX Subsection "EXAMPLE: Working as mutex and counting semaphore" The command \fBsem\fR is an alias for \fBparallel \-\-semaphore\fR. .PP 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 \fBsem\fR will wait for one of these to complete before starting another command. \fBsem \-\-wait\fR will wait for all jobs to complete. .PP Run 10 jobs concurrently in the background: .PP .Vb 5 \& for i in *.log ; do \& echo $i \& sem \-j10 gzip $i ";" echo done \& done \& sem \-\-wait .Ve .PP A mutex is a counting semaphore allowing only one job to run. This will edit the file \fImyfile\fR and prepends the file with lines with the numbers 1 to 3. .PP .Vb 1 \& seq 3 | parallel sem sed \-i \-e \*(Aq1i{}\*(Aq myfile .Ve .PP As \fImyfile\fR can be very big it is important only one process edits the file at the same time. .PP Name the semaphore to have multiple different semaphores active at the same time: .PP .Vb 1 \& seq 3 | parallel sem \-\-id mymutex sed \-i \-e \*(Aq1i{}\*(Aq myfile .Ve .SS "EXAMPLE: Mutex for a script" .IX Subsection "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 \fBsem\fR and \fB\-\-shebang\-wrap\fR the script can be made to wait for other instances to finish. Here in \&\fBbash\fR: .PP .Vb 1 \& #!/usr/bin/sem \-\-shebang\-wrap \-u \-\-id $0 \-\-fg /bin/bash \& \& echo This will run \& sleep 5 \& echo exclusively .Ve .PP Here \fBperl\fR: .PP .Vb 1 \& #!/usr/bin/sem \-\-shebang\-wrap \-u \-\-id $0 \-\-fg /usr/bin/perl \& \& print "This will run "; \& sleep 5; \& print "exclusively\en"; .Ve .PP Here \fBpython\fR: .PP .Vb 1 \& #!/usr/local/bin/sem \-\-shebang\-wrap \-u \-\-id $0 \-\-fg /usr/bin/python \& \& import time \& print "This will run "; \& time.sleep(5) \& print "exclusively"; .Ve .SS "EXAMPLE: Start editor with file names from stdin (standard input)" .IX Subsection "EXAMPLE: Start editor with file names from stdin (standard input)" You can use GNU \fBparallel\fR to start interactive programs like emacs or vi: .PP .Vb 2 \& cat filelist | parallel \-\-tty \-X emacs \& cat filelist | parallel \-\-tty \-X vi .Ve .PP If there are more files than will fit on a single command line, the editor will be started again with the remaining files. .SS "EXAMPLE: Running sudo" .IX Subsection "EXAMPLE: Running sudo" \&\fBsudo\fR 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 \fBsudo\fR for a while. .PP The command: .PP .Vb 1 \& parallel sudo echo ::: This is a bad idea .Ve .PP is no good, as you would be prompted for the sudo password for each of the jobs. Instead do: .PP .Vb 1 \& sudo parallel echo ::: This is a good idea .Ve .PP This way you only have to enter the sudo password once. .SS "EXAMPLE: Run ping in parallel" .IX Subsection "EXAMPLE: Run ping in parallel" \&\fBping\fR prints out statistics when killed with CTRL-C. .PP Unfortunately, CTRL-C will also normally kill GNU \fBparallel\fR. .PP But by using \fB\-\-open\-tty\fR and ignoring SIGINT you can get the wanted effect: .PP .Vb 2 \& parallel \-j0 \-\-open\-tty \-\-lb \-\-tag ping \*(Aq{= $SIG{INT}=sub {} =}\*(Aq \e \& ::: 1.1.1.1 8.8.8.8 9.9.9.9 21.21.21.21 80.80.80.80 88.88.88.88 .Ve .PP \&\fB\-\-open\-tty\fR will make the \fBping\fRs receive SIGINT (from CTRL-C). CTRL-C will not kill GNU \fBparallel\fR, so that will only exit after \&\fBping\fR is done. .SS "EXAMPLE: GNU Parallel as queue system/batch manager" .IX Subsection "EXAMPLE: GNU Parallel as queue system/batch manager" GNU \fBparallel\fR can work as a simple job queue system or batch manager. The idea is to put the jobs into a file and have GNU \fBparallel\fR read from that continuously. As GNU \fBparallel\fR will stop at end of file we use \fBtail\fR to continue reading: .PP .Vb 1 \& true >jobqueue; tail \-n+0 \-f jobqueue | parallel .Ve .PP To submit your jobs to the queue: .PP .Vb 1 \& echo my_command my_arg >> jobqueue .Ve .PP You can of course use \fB\-S\fR to distribute the jobs to remote computers: .PP .Vb 1 \& true >jobqueue; tail \-n+0 \-f jobqueue | parallel \-S .. .Ve .PP Output only will be printed when reading the next input after a job has finished: So you need to submit a job after the first has finished to see the output from the first job. .PP If you keep this running for a long time, jobqueue will grow. A way of removing the jobs already run is by making GNU \fBparallel\fR stop when it hits a special value and then restart. To use \fB\-\-eof\fR to make GNU \&\fBparallel\fR exit, \fBtail\fR also needs to be forced to exit: .PP .Vb 10 \& true >jobqueue; \& while true; do \& tail \-n+0 \-f jobqueue | \& (parallel \-E StOpHeRe \-S ..; echo GNU Parallel is now done; \& perl \-e \*(Aqwhile(<>){/StOpHeRe/ and last};print <>\*(Aq jobqueue > j2; \& (seq 1000 >> jobqueue &); \& echo Done appending dummy data forcing tail to exit) \& echo tail exited; \& mv j2 jobqueue \& done .Ve .PP In some cases you can run on more CPUs and computers during the night: .PP .Vb 7 \& # 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 .. .Ve .PP GNU \fBparallel\fR discovers if \fBjobfile\fR or \fB~/.parallel/sshloginfile\fR changes. .SS "EXAMPLE: GNU Parallel as dir processor" .IX Subsection "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 \fBinotifywait\fR is called on other platforms file a bug report): .PP .Vb 2 \& inotifywait \-qmre MOVED_TO \-e CLOSE_WRITE \-\-format %w%f my_dir |\e \& parallel \-u echo .Ve .PP This will run the command \fBecho\fR on each file put into \fBmy_dir\fR or subdirs of \fBmy_dir\fR. .PP You can of course use \fB\-S\fR to distribute the jobs to remote computers: .PP .Vb 2 \& inotifywait \-qmre MOVED_TO \-e CLOSE_WRITE \-\-format %w%f my_dir |\e \& parallel \-S .. \-u echo .Ve .PP 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. .PP Using GNU \fBparallel\fR as dir processor has the same limitations as using GNU \fBparallel\fR as queue system/batch manager. .SS "EXAMPLE: Locate the missing package" .IX Subsection "EXAMPLE: Locate the missing package" If you have downloaded source and tried compiling it, you may have seen: .PP .Vb 4 \& $ ./configure \& [...] \& checking for something.h... no \& configure: error: "libsomething not found" .Ve .PP 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://codeberg.org/tange/tangetools can tell which files a program tried to access. In this case we are interested in one of the last files: .PP .Vb 1 \& $ tracefile \-un ./configure | tail | parallel \-j0 apt\-file search .Ve .SH AUTHOR .IX Header "AUTHOR" When using GNU \fBparallel\fR for a publication please cite: .PP O. Tange (2011): GNU Parallel \- The Command-Line Power Tool, ;login: The USENIX Magazine, February 2011:42\-47. .PP This helps funding further development; and it won't cost you a cent. If you pay 10000 EUR you should feel free to use GNU Parallel without citing. .PP Copyright (C) 2007\-10\-18 Ole Tange, http://ole.tange.dk .PP Copyright (C) 2008\-2010 Ole Tange, http://ole.tange.dk .PP Copyright (C) 2010\-2024 Ole Tange, http://ole.tange.dk and Free Software Foundation, Inc. .PP Parts of the manual concerning \fBxargs\fR compatibility is inspired by the manual of \fBxargs\fR from GNU findutils 4.4.2. .SH LICENSE .IX Header "LICENSE" This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or at your option any later version. .PP This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. .PP You should have received a copy of the GNU General Public License along with this program. If not, see . .SS "Documentation license I" .IX Subsection "Documentation license I" Permission is granted to copy, distribute and/or modify this documentation under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the file LICENSES/GFDL\-1.3\-or\-later.txt. .SS "Documentation license II" .IX Subsection "Documentation license II" You are free: .IP "\fBto Share\fR" 9 .IX Item "to Share" to copy, distribute and transmit the work .IP "\fBto Remix\fR" 9 .IX Item "to Remix" to adapt the work .PP Under the following conditions: .IP \fBAttribution\fR 9 .IX Item "Attribution" You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). .IP "\fBShare Alike\fR" 9 .IX Item "Share Alike" If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. .PP With the understanding that: .IP \fBWaiver\fR 9 .IX Item "Waiver" Any of the above conditions can be waived if you get permission from the copyright holder. .IP "\fBPublic Domain\fR" 9 .IX Item "Public Domain" Where the work or any of its elements is in the public domain under applicable law, that status is in no way affected by the license. .IP "\fBOther Rights\fR" 9 .IX Item "Other Rights" In no way are any of the following rights affected by the license: .RS 9 .IP \(bu 2 Your fair dealing or fair use rights, or other applicable copyright exceptions and limitations; .IP \(bu 2 The author's moral rights; .IP \(bu 2 Rights other persons may have either in the work itself or in how the work is used, such as publicity or privacy rights. .RE .RS 9 .RE .IP \fBNotice\fR 9 .IX Item "Notice" For any reuse or distribution, you must make clear to others the license terms of this work. .PP A copy of the full license is included in the file as LICENCES/CC\-BY\-SA\-4.0.txt .SH "SEE ALSO" .IX Header "SEE ALSO" \&\fBparallel\fR(1), \fBparallel_tutorial\fR(7), \fBenv_parallel\fR(1), \&\fBparset\fR(1), \fBparsort\fR(1), \fBparallel_alternatives\fR(7), \&\fBparallel_design\fR(7), \fBniceload\fR(1), \fBsql\fR(1), \fBssh\fR(1), \&\fBssh-agent\fR(1), \fBsshpass\fR(1), \fBssh-copy-id\fR(1), \fBrsync\fR(1)