$ XARGS 命令

Linux XARGS 管道符

Posted by gomyck on November 28, 2019

xrags 的简单使用

linux 和 unix 的命令都带有参数, 有的命令可以直接使用标准输入 stdin 来作为参数, 如下实例:

1
2
3
4
# 查找 ck.log 中的 gomyck 关键字
$ cat /usr/share/gomyck/ck.log | grep gomyck

下面是 grep 命令的描述:

1
2
3
4
5
6
7
8
DESCRIPTION
   grep  searches  the  named  input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is
   given as file name) for lines containing a match to the given PATTERN.  By default, grep prints the matching lines.

   In addition, two variant programs egrep and fgrep are available.  egrep is the same as grep -E.  fgrep is  the  same
   as  grep -F.   Direct  invocation  as  either  egrep  or  fgrep  is  deprecated, but is provided to allow historical
   applications that rely on them to run unmodified.

可以看出, grep 是可以接受标准输入的命令

但是有些命令不能接受标准输入, 管道符失去了作用, 只能在命令行输入参数

1
2
3
4
#不好用
$ tail -n 10 ck.log | echo

上述命令无输出, 可以看出 echo 不接受标准输入作为参数

xargs 的使用

xargs 的作用是把标准输入转化成命令行参数, 所以一般来说, xargs 总是和管道符 | 一起搭配使用

1
2
$ tail -n 10 ck.log | xargs echo

使用方式: xargs [-options] [command]

xargs 默认的 command 是 echo

1
2
3
4
5
6
$ xargs
$ hello world
# ctrl + d
# echo
$ hello world

xargs 的描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
DESCRIPTION
     The xargs utility reads space, tab, newline and end-of-file delimited strings from
     the standard input and executes utility with the strings as arguments.

     Any arguments specified on the command line are given to utility upon each invoca-
     tion, followed by some number of the arguments read from the standard input of
     xargs.  The utility is repeatedly executed until standard input is exhausted.

     Spaces, tabs and newlines may be embedded in arguments using single (`` ' '') or
     double (``"'') quotes or backslashes (``\'').  Single quotes escape all non-single
     quote characters, excluding newlines, up to the matching single quote.  Double
     quotes escape all non-double quote characters, excluding newlines, up to the
     matching double quote.  Any single character, including newlines, may be escaped
     by a backslash.

xargs 默认约定以空格 tab 换行符 结束符来分隔字符串, 用来作为给定命令的参数, 也可以使用-d 参数来指定分隔字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ echo "gomyck1 gomyck2 gomyck3" | xargs mkdir

# echo -e 表示解释参数中的转译字符 \t
$ echo -e "gomyck1\tgomyck2\tgomyck3" | xargs -d "\t" mkdir

# xargs -p 会有用户确认过程, 输入 y 后才真正执行命令
$ echo -e "gomyck1\tgomyck2\tgomyck3" | xargs -d -p "\t" mkdir

# xargs -t 直接执行命令, 并打印
$ echo -e "gomyck1\tgomyck2\tgomyck3" | xargs -d -t "\t" mkdir

# find -print0 把查找结果按 null 分组, xargs -0 以 null 为分隔符
$ find / -name etc  -print0 | xargs -0 echo

# 打印文件, 删除文件  param 为占位符, sh -c 为执行命令
$ echo /usr/share/gomyck/ck.log | xargs -I param sh -c 'echo param; rm -rf param'

其他知识点

在VMware Workstation中,默认有三个虚拟交换机VMnet0用于桥接,VMnet1用于仅主机网络,VMnet8用于NAT