others-how to use xargs with params in middle of the command

1. Purpose

In this post, I would show how to use xargs with params in middle of the command.



2. The solution

2.1 The scenerio

For example, we want to do the following jobs:

  • 1) Find the pid of process which contains nginx -g:

    • ps aux|grep "nginx -g"
      
  • 2) Then we want to print the thread status of the process(say the pid is 7245):

    • cat /proc/7245/status|grep -i threads
      


2.2 The solution

2.2.1 What is xargs?

xargs is a command on Unix and most Unix-like operating systems used to build and execute commands from standard input. It converts input from standard input into arguments to a command. Some commands such as grep and awk can take input either as command-line arguments or from the standard input.

Syntax of xargs:

xargs [-0prtx] [-E eof-str] [-e[eof-str]] [–eof[=eof-str]] [–null] [-d delimiter] [–delimiter delimiter] [-I replace-str] [-i[replace-str]] [–replace[=replace-str]] [-l[max-lines]] [-L max-lines] [–max-lines[=max-lines]] [-n max-args] [–max-args=max-args] [-s max-chars] [–max-chars=max-chars] [-P max-procs] [–max-procs=max-procs] [–interactive] [–verbose] [–exit] [–no-run-if-empty] [–arg-file=file] [–show-limits] [–version] [–help] [command [initial-arguments]]

2.2.2 Examples of xargs

Example #1: execute command from input one by one:

➜  ~ echo a b c d e f| xargs
a b c d e f

Example #2: xargs with find

$ find . -name '*.h' | xargs grep 'stdlib.h'


2.2.3 How to use xargs to do the job in one command line?

Now we want to use xargs to do the job in one line instead of two lines of command, just as follows:

Here is the final command:

$ ps aux|grep "nginx -g"|grep -v grep|awk '{print $2}'|xargs -I pid sh -c 'cat /proc/pid/status|grep -i threads'


The grep -v grep means to exclude the lines that contains grep string.

grep -v, –invert-match Selected lines are those not matching any of the specified pat- terns.

The awk '{print $2}' means to catch the second field of the line:

awk ‘{ print $2; }’ prints the second field of each line. This field happens to be the process ID from the ps aux output.

The xargs -I pid tells xargs to replace pid with the real value of pid in the subsequent commands.

xargs -I replace-str

Replace occurrences of replace-str in the initial arguments with names read from standard input. Also, unquoted blanks do not terminate arguments; instead, the input is split at newlines only. If replace-str is omitted (omitting it is allowed only for ‘-i’), it defaults to ‘{}’ (like for ‘find -exec’). Implies ‘-x’ and ‘-l 1’. The ‘-i’ option is deprecated in favour of the ‘-I’ option.

3. Summary

In this post, I demonstrated how to use one line of command to find the process ID and then use the PID to do some jobs, the key point is to use xargs -I . That’s it, thanks for your reading.

-->