Bash - Xargs (Standard input command execution)

Card Puncher Data Processing

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 





Discover More
Bash Liste Des Attaques Ovh
Bash - (Argument|Positional Parameter)

An argument is a parameter given: to a command to a function or to the bash shell They are referenced by position. A positional parameter is a parameter denoted: by one or more digits, ...
Bash Liste Des Attaques Ovh
Bash - Command Execution

To execute a command in a script command substitution with: $( ) in a subshell backticks `` in the same shell from a string in a subshell from standard input See also: You can execute...
Card Puncher Data Processing
How to replace in bulk a text in multiple file with a bash pipeline

An step by step that shows you how to create bash pipeline to replace in bulk text in files



Share this page:
Follow us:
Task Runner