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
参考
- ^ GNU Core Utilities FAQ. [2008-03-12]. (原始内容存档于2020-11-11).
外部链接
xargs
: construct argument lists and invoke utility – 命令与工具(Commands & Utilities)参考,单一UNIX®规范第7期,由國際開放標準組織发布
手册页
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)参考手册页
- 查
- 论
- 编
- cat
- cd
- chmod
- chown
- chgrp
- cksum
- cmp
- cp
- dd
- du
- df
- file
- fsck
- fuser
- ln
- ls
- mkdir
- mount
- mv
- pax(英语:pax (Unix))
- pwd
- rm
- rmdir
- size
- split
- stat
- tee
- touch
- type(英语:type (Unix))
- umask(英语:umask)
- at
- bg
- chroot
- cron
- fg
- kill
- killall(英语:killall)
- nice
- pgrep
- pkill(英语:pkill)
- ps
- pstree(英语:pstree)
- time
- top
- 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
- alias
- echo
- printf格式字符串
- test(英语:test (Unix))
- unset
- wait
- apropos(英语:apropos (Unix))
- help(英语:help (command))
- man