Table of Contents

Bash - Xargs (Standard input command execution)

About

wiki/xargs is an utility that takes the output of a command (ie standard input in a stream) to create arguments and execute commands. This command does not take in general a stream as argument).

Example

Use argument as placeholder

By default, the data is appended to the end of the command as an argument.

It can be used in a placeholder. The traditional placeholder is {};

Example:

echo "World" | xargs -I {} echo "Hello {}"

More complicated. The command line of a process (started with the command k3s server)

# Grep the process with `k3s server`
ps aux | grep "k3s server" | \
   # Suppress the grep itself from the list
   grep -v grep | \
   # Take the process id (ie 2 argument)
   awk '{print $2}' | \
   # Transform the input to arguments with xargs
   xargs -I {} cat /proc/{}/cmdline | \
   # Delete the null character and transform space as new line
   tr '\0' ' ' | tr ' ' '\n'

remove file

find /path -type f -print | xargs rm

Parse arguments and use only argument 3

If you have an output that returns data in an argument form (such as trap -p), you can still parse them and pass them via xargs and bash

echo trap -- \'echo error\' ERR |  \
  xargs -l bash -c 'echo This is the third argument: $2'
This is the third argument: echo error

other example with hdfs

hdfs dfs -ls /path | grep -e pattern | awk '{print $8}' | xargs hdfs dfs -rm