Linux 下xargs命令详解及xargs与管道的区别

2019-09-23 09:09:48于丽

输入中读取要处理的内容了。

另外很多程序是不处理标准输入的,例如 kill , rm 这些程序如果命令行参数中没有指定要处理的内容则不会默认从标准输入中读取。所以:

echo '516' | kill

这种命里是不能执行的。

echo 'test' | rm -f

这种也是没有效果的。

这两个命令只接受命令行参数中指定的处理内容,不从标准输入中获取处理内容。想想也很正常,kill 是结束进程,rm是删除文件,如果要结束的进程pid和要删除的文件名需要
从标准输入中读取,这个也很怪异吧。 但是像 cat与grep这些文字处理工具从标准输入中读取待处理的内容则很自然。

但是有时候我们的脚本却需要 echo '516' | kill 这样的效果,例如 ps -ef | grep 'ddd' | kill 这样的效果,筛选出符合某条件的进程pid然后结束。这种需求对于我们来说是理所当然而且是很常见的,那么应该怎样达到这样的效果呢。有几个解决办法:

1. 通过

kill `ps -ef | grep 'ddd'` 

#这种形式,这个时候实际上等同于拼接字符串得到的命令,其效果类似于  kill $pid

2.

for procid in $(ps -aux | grep "some search" | awk '{print $2}'); do kill -9 $procid; done 

#其实与第一种原理一样,只不过需要多次kill的时候是循环处理的,每次处理一个

3.

 ps -ef | grep 'ddd' | xargs kill 

#OK,使用了xargs命令,铺垫了这么久终于铺到了主题上。xargs命令可以通过管道接受字符串,并将接收到的字符串通过空格分割成许多参数(默认情况下是通过空格分割) 然后将参数传递给其后面的命令,作为后面命令的命令行参数

xargs是什么,与管道有什么不同

xargs与管道有什么不同呢,这是两个很容易混淆的东西,看了上面的xargs的例子还是有点云里雾里的话,我们来看下面的例子弄清楚为什么需要xargs:

echo '--help' | cat 

输出:

--help
echo '--help' | xargs cat 

输出:

Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s), or standard input, to standard output.
 -A, --show-all   equivalent to -vET
 -b, --number-nonblank number nonempty output lines
 -e      equivalent to -vE
 -E, --show-ends   display $ at end of each line
 -n, --number    number all output lines
 -s, --squeeze-blank  suppress repeated empty output lines
 -t      equivalent to -vT
 -T, --show-tabs   display TAB characters as ^I
 -u      (ignored)
 -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
  --help  display this help and exit
  --version output version information and exit
With no FILE, or when FILE is -, read standard input.
Examples:
 cat f - g Output f's contents, then standard input, then g's contents.
 cat  Copy standard input to standard output.
Report cat bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'cat invocation'