Xargs

xargs是一条Unix和类Unix操作系统的常用命令。它的作用是将参数列表转换成小块分段传递给其他命令,以避免参数列表过长的问题[1]。xargs的作用一般等同于大多数Unix shell中的反引号,但更加灵活易用,并可以正确处理输入中有空格等特殊字符的情况。对于经常产生大量输出的命令如find、locate和grep来说非常有用。

示例

例如,下面的命令:

rm $(find /path -type f)

如果path目录下文件过多就会因为“参数列表过长”而报错无法执行。但改用xargs以后,问题即获解决。

find /path -type f -print0 | xargs -0 rm

本例中xargs将find产生的长串文件列表拆散成多个子串,然后对每个子串调用rm。-print0表示輸出以null分隔(-print使用換行);-0表示輸入以null分隔。这样要比如下使用find命令效率高的多。

find /path -type f -exec rm '{}' \;

上面这条命令会对每个文件调用"rm"命令。当然使用新版的"find"也可以得到和"xargs"命令同样的效果:

find /path -type f -exec rm '{}' +
find . -name "*.foo" | xargs grep bar

该命令大体等价于

grep bar $(find . -name "*.foo")
find . -name "*.foo" -print0 | xargs -0 grep bar

使用了GNU特殊规定的空字符。

find . -name "*.foo" -print0 | xargs -0 -t -r vi

与上面的基本相同但启动vi进行编辑。-t参数会提前打印错误信息。-r参数是一个GNU扩展,表明在无输入情况下则不构造命令执行。

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

使用-i参数将{}中内容替换为列表中的内容。

参见

  • GNU parallel
  • pexec

参考

  1. ^ GNU Core Utilities FAQ. [2008-03-12]. (原始内容存档于2020-11-11). 

外部链接

手册页

  • xargs(1) – GNU Findutils参考
  • xargs(1): construct argument list(s) and execute utility – FreeBSD通用命令(General Commands)手册页
  • xargs(1): construct argument list(s) and execute utility – NetBSD通用命令(General Commands)手册页
  • xargs(1): construct argument list(s) and execute utility – OpenBSD通用命令(General Commands)手册页
  • xargs(1): construct argument lists and invoke utility – Solaris 10用户命令(User Commands)参考手册页
文件系統
程序
  • at
  • bg
  • chroot
  • cron
  • fg
  • kill
  • killall英语killall
  • nice
  • pgrep
  • pkill英语pkill
  • ps
  • pstree英语pstree
  • time
  • top
用户环境
  • clear
  • env
  • exit
  • history英语history (Unix)
  • id
  • logname
  • mesg英语mesg
  • passwd
  • su
  • sudo
  • uptime
  • talk英语talk (software)
  • tput英语tput
  • uname
  • w
  • wall英语wall (Unix)
  • who
  • whoami
  • write英语write (Unix)
文本编辑
  • awk
  • banner英语banner (Unix)
  • basename
  • comm英语comm
  • csplit英语csplit
  • cut
  • diff
  • dirname
  • ed
  • ex
  • fmt英语fmt
  • fold英语fold (Unix)
  • head英语head (Unix)
  • iconv
  • join英语join (Unix)
  • less
  • more
  • nl英语nl (Unix)
  • paste英语paste (Unix)
  • sed
  • sort英语sort (Unix)
  • spell英语spell (Unix)
  • strings英语strings (Unix)
  • tail
  • tr
  • uniq英语uniq
  • vi
  • wc
  • xargs
壳层内建
网络
查找
文档
  • apropos英语apropos (Unix)
  • help英语help (command)
  • man
软件开发
杂项
  • bc
  • cal
  • dc
  • expr
  • lp英语lp (Unix)
  • lpr
  • sleep
  • true和false
  • yes