Answers:
您会混淆两种非常不同的输入:STDIN和参数。参数是在启动时提供给命令的字符串的列表,通常通过在命令名称之后指定它们(例如echo these are some arguments
或rm file1 file2
)来指定。另一方面,STDIN是命令启动后可以(可选)读取的字节流(有时是文本,有时不是)。以下是一些示例(请注意,cat
可以使用参数或STDIN,但它们的作用不同):
echo file1 file2 | cat # Prints "file1 file2", since that's the stream of
# bytes that echo passed to cat's STDIN
cat file1 file2 # Prints the CONTENTS of file1 and file2
echo file1 file2 | rm # Prints an error message, since rm expects arguments
# and doesn't read from STDIN
xargs
可以认为是将STDIN样式的输入转换为参数:
echo file1 file2 | cat # Prints "file1 file2"
echo file1 file2 | xargs cat # Prints the CONTENTS of file1 and file2
echo
实际上实际上是相反的:将其参数转换为STDOUT(可以通过管道将其传递到其他命令的STDIN):
echo file1 file2 | echo # Prints a blank line, since echo doesn't read from STDIN
echo file1 file2 | xargs echo # Prints "file1 file2" -- the first echo turns
# them from arguments into STDOUT, xargs turns
# them back into arguments, and the second echo
# turns them back into STDOUT
echo file1 file2 | xargs echo | xargs echo | xargs echo | xargs echo # Similar,
# except that it converts back and forth between
# args and STDOUT several times before finally
# printing "file1 file2" to STDOUT.
ls | grep -v "notes.txt" | xargs rm
除了notes.txt
或通常从不解析ls
output之外,您不应使用它来删除所有内容。例如,如果单个文件包含空格,则命令将中断。更安全的方法是rm !(notes.txt)
使用Bash(带有shopt -s extglob
set)或rm ^notes.txt
Zsh(带有EXTENDED_GLOB
)等