Linux xargs: запуск утилит на список, простая многопоточность в bash

xargs позволяет легко запускать утилиты на списки аргументов, даже если утилиты не поддерживают работу со списками. Реализуется простейшим образом – xargs каждый раз заново вызывает утилиту при запуске на список. Например, можно создать на основе списка множество директорий с помощью mkdir.

xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments
bash-3.2$ cat dir_lst.txt 
dir1
dir2
dir3

bash-3.2$ cat dir_lst.txt | xargs mkdir

bash-3.2$ ls -ltr | grep dir
-rw-r--r-- 1 petrredkin staff 15 Apr 13 22:42 dir_lst.txt
drwxr-xr-x 2 petrredkin staff 64 Apr 13 22:43 dir1
drwxr-xr-x 2 petrredkin staff 64 Apr 13 22:43 dir2
drwxr-xr-x 2 petrredkin staff 64 Apr 13 22:43 dir3

 

Simple threads

Простая многопоточность в bash: делаем скрипт для одной сети/одного IP (с любым из скнов представленных ниже, например), далее делаем список сетей/IP, открываем его через cat и натравляем скрипт через xargs.

cat nets | xargs -n 1 -I ^ -P 10 bin/test ^

 

CURL

(curl/wget, xargs) многопроцессный curl

seq 1 10000 | xargs -n 1 -P 10 ./curl.sh &>test_log.10k.10p.log

cat curl.sh
>&2 echo "Transaction ID $1 started"
curl "https://srv.test:443/1024b.txt" -v -o 1024b.$1.txt
md5=$(md5sum 1024b.$1.txt)
>&2 echo "Transaction ID $1 result $md5"
rm 1024b.$1.txt
>&2 echo "Transaction ID $1 finished"

для многопоточности в рамках каждого процесса потенциально можно использовать опции curl по параллельным запросам в потоках

The cURL -Z or --parallel options are used to pass a list of URLs to request in parallel. For this parallel execution, cURL can handle up to 50 operations at the same time.
questions

What is the purpose of the xargs command?

A. It passes arguments to an X server.
B. It reads standard input (STDIN) and builds up command lines to execute.
C. It helps shellscripts take variable argument lists.
D. It asks a question, graphically, and returns the answer to the shell.
E. It allows users to specify long options for commands that normally only accept short options.

Answer: B

The purpose of the xargs command is to read standard input (STDIN) and build up command lines to execute. The xargs command can be used to pass arguments to another command that does not accept input from a pipe.

 

Leave a Reply