Xargs 命令

 

Xargs 简介

xargs 的作用是将参数列表转换成小块分段传递给其他命令,以避免参数列表过长的问题

xargs [options] [command]

xargs 从标准输入读取数据,将数据转换为 command 命令的参数来执行该命令。如果没有指定命令,使用/bin/echo作为默认命令。

-t 选项

-t选项将执行的命令行先打印出来,然后再执行命令。

$ ls -1 /tmp | xargs -t
echo readme.md requirements.txt
readme.md requirements.txt

-0 选项

-0选项以null作为分隔符,用于处理含有空格引号反斜杠这样字符的输入数据(如文件名中含有空格),通常与find -print0命令配合

$ find . -type f -print0
./readme.md./requirements.txt

$ find . -type f -print0 | xargs -0
./readme.md ./requirements.txt

-I 或 -i 选项

-i选项已经被弃用,使用-I来替代,指定一个替换字符串,比如 {}%,在 xargs 执行的命令中将{}替换为参数列表中的内容,该选项隐含了-x-L 1选项

find . -name "*.foo" -print0 | xargs -0 -I {} mv {} /tmp/trash

find . -name "*.crt" -print0 | xargs -0 -I% openssl x509 -noout -subject -enddate -in %

-n 选项

-n选项默认使用空格和换行符作为分隔符从标准输入读取数据,指定传递给 command 的参数个数

$ echo -e "a\nb c\nd" | xargs -n1
a
b
c
d

$ echo -e "a\nb c\nd" | xargs -n2
a b
c d

-L 选项

-L选项默认使用换行符作为分隔符从标准输入读取数据,指定传递给 command 的参数个数

$ echo -e "a\nb c\nd" | xargs -L1
a
b c
d

$ echo -e "a\nb c\nd" | xargs -L2
a b c
d

-d 选项

-d选项指定从标准读入数据时的分隔符

$ echo 'a!b!c' | xargs -d'!' -n1
a
b
c

在 xargs 命令中使用管道或重定向

可以在 xargs 命令中使用 sh -c 命令来获得完整的命令行功能

  • 打印本地所有8xxx或9xxx端口的证书
netstat -tulpn | grep -Pwo '(?:8|9)\d{3}' | xargs -I% -n1 sh -c 'echo | openssl s_client -connect localhost:% 2>/dev/null | openssl x509'
  • 打印当前目录及子目录下的证书信息,证书间用空行分隔
find . -name '*.pem' | xargs -I% sh -c 'echo; openssl x509 -noout -in % -subject -dates -ext subjectAltName'