The xargs
实用程序允许您从标准输入构建和执行命令。它通常通过管道与其他命令结合使用。
With xargs
,您可以提供标准输入作为命令行实用程序的参数,例如mkdir
and rm
.
在本教程中,我们将介绍使用xargs
命令。
如何使用Linuxxargs
命令#
xargs
从标准输入读取参数,以空格或换行符分隔,并使用输入作为命令的参数来执行指定的命令。如果没有提供命令,则默认为/bin/回声
.
语法为xargs
命令如下:
xargs [OPTIONS] [COMMAND [initial-arguments]]
最基本的使用示例xargs
是使用管道传递几个用空格分隔的字符串xargs
并运行一个将使用这些字符串作为参数的命令。
echo "file1 file2 file3" | xargs touch
在上面的示例中,我们将标准输入通过管道传输到xargs
,以及touch针对每个参数运行命令,创建三个文件。这与运行以下命令相同:
如何查看命令并提示用户#
要在执行命令之前在终端上打印命令,请使用-t
(--verbose
) 选项:
echo "file1 file2 file3" | xargs -t touch
touch file1 file2 file3
如果您想在执行每个命令之前获得是否运行每个命令的提示,请使用-p
(--interactive
) 选项:
echo "file1 file2 file3" | xargs -p touch
Type y
or Y
确认并运行命令:
touch file1 file2 file3 ?...y
该选项在执行破坏性命令时非常有用。
如何限制参数数量#
默认情况下,传递给命令的参数数量由系统限制决定。
The -n
(--max-args
) 选项指定要传递给给定命令的参数数量。xargs
根据需要多次运行指定的命令,直到用尽所有参数。
在以下示例中,从标准输入读取的参数数量限制为 1。
echo "file1 file2 file3" | xargs -n 1 -t touch
从下面的详细输出中可以看到,touch 命令是针对每个参数单独执行的:
touch file1
touch file2
touch file3
如何运行多个命令#
运行多个命令xargs
, 使用-I
选项。它的工作原理是定义一个replace-str
之后-I
选项和所有出现的replace-str
替换为传递给 xargs 的参数。
下列xargs
示例将运行两个命令,首先它将使用以下命令创建文件touch
,然后它会列出带有ls命令:
echo "file1 file2 file3" | xargs -t -I % sh -c '{ touch %; ls -l %; }'
-rw-r--r-- 1 linuxize users 0 May 6 11:54 file1
-rw-r--r-- 1 linuxize users 0 May 6 11:54 file2
-rw-r--r-- 1 linuxize users 0 May 6 11:54 file3
一个常见的选择replace-str
is %
。但是,您可以使用其他占位符,例如,ARGS
:
echo "file1 file2 file3" | xargs -t -I ARGS sh -c '{ touch ARGS; ls -l ARGS; }'
如何指定分隔符#
Use the -d
(--delimiter
) 选项设置自定义分隔符,可以是单个字符,也可以是以以下字符开头的转义序列\
.
下面我们使用的例子;
作为分隔符:
echo "file1;file2;file3" | xargs -d \; -t touch
touch file1 file2 file3
如何从文件中读取项目#
xargs 命令还可以从文件而不是标准输入中读取项目。为此,请使用-a
(--arg-file
) 选项后跟文件名。
在下面的示例中,xargs
命令将读取ips.txt
文件并 ping 每个 IP 地址。
ips.txt
我们还使用-L 1
选项,指示xargs
一次读一行。如果省略该选项xargs
会将所有 IP 传递给一个ping命令。
xargs -t -L 1 -a ips.txt ping -c 1
ping -c 1 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=50 time=68.1 ms
...
ping -c 1 1.1.1.1
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=59 time=21.4 ms
Using xargs
with find
#
xargs
最常与以下组合使用find命令。您可以使用find
搜索特定文件,然后使用xargs
对这些文件执行操作。
为了避免包含换行符或其他特殊字符的文件名出现问题,请始终使用 find-print0
选项,这会导致find
打印完整的文件名,后跟一个空字符。此输出可以通过以下方式正确解释xargs
使用-0
, (--null
) 选项。
在下面的示例中,find
将打印里面所有文件的全名/var/www/.cache
目录和xargs
将文件路径传递给rm命令:
find /var/www/.cache -type f -print0 | xargs -0 rm -f
使用 xargs 修剪空白字符#
xargs
也可以用作删除给定字符串两侧空格的工具。只需将字符串通过管道传输到xargs
命令,它将进行修剪:
echo " Long line " | xargs
Long line
这在以下情况下很有用:比较字符串在 shell 脚本中。
#!/bin/bash
VAR1=" Linuxize "
VAR2="Linuxize"
if [[ "$VAR1" == "$VAR2" ]]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi
## Using xargs to trim VAR1
if [[ $(echo "$VAR1" | xargs) == "$VAR2" ]]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi
Strings are not equal.
Strings are equal.
结论#
xargs
是 Linux 上的命令行实用程序,使您能够构建和执行命令。
有关每个的更多详细信息xargs
选项,阅读xargs人
page.
如果您有任何问题或反馈,请随时发表评论。