Back to TILs

xargs

Date: 2023-02-21Last modified: 2023-03-07

Table of contents

Introduction

xargs build and execute command lines from standard input.

Replacement string

seq 10 | xargs -I {} echo "{}² = {} x {}"

The -I {} indicates the replacement string. In this example all occurrences of {} will be replaced by the input line. The output of previous command is depicted below:

1² = 1 x 1
2² = 2 x 2
3² = 3 x 3
4² = 4 x 4
5² = 5 x 5
6² = 6 x 6
7² = 7 x 7
8² = 8 x 8
9² = 9 x 9
10² = 10 x 10

How to stop on first error?

General method

xargs -n 1 sh -c '<your_command> $0 || exit 255' < input

Specific case

xargs -n 1 sh -c 'curl --silent --output /dev/null \
  --write-out "%{url_effective}: %{http_code}\n" $0 || exit 255' < pages.txt

References