rom*_*her 2 unix macos bash terminal
我正在学习如何在bash中使用I/O重定向,并尝试使用管道的一些示例:
pwd | say
ls -l | grep "staff" > out.txt
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用两者pwd并open使用管道重定向时,命令失败,我只是收到open使用情况.
我正在尝试的是: pwd | open
从bash打开当前目录的正确方法是什么?
事后看来,有两个截然不同的答案:
答:要回答的任择议定书的问题作为询问,以了解管道和I/O流:
echo . | xargs open
# Equivalent solution, using the special "$PWD" shell variable.
printf '%s\0' "$PWD" | xargs -0 open
Run Code Online (Sandbox Code Playgroud)
是通过管道将当前目录的路径传递给openCLI 的最强大的方法,以便在OSX的文件系统浏览器GUI应用程序中打开该目录.Finder
请注意,pwd | xargs open它不健壮,因为如果当前目录路径嵌入了空格,它将失败 - 请参阅下文.
open要求输入通过命令行参数而不是通过stdin输入流提供,就像这里的情况一样(通过管道|).xargs实用程序.xargs接受stdin输入 - 在这种情况下来自管道 - 并使用标记化的stdin输入 作为该命令的参数调用指定为其参数的命令(open在本例中).xargs默认情况下按空格拆分:
.作为输入,没有分裂(或解释由shell)发生,因此它可以只被echo编到xargs.$PWDshell变量(总是包含当前dir.的完整路径)可能包含嵌入的空格,因此需要额外的步骤来确保它open作为单个参数传递:
printf '%s\0' "$PWD"打印当前目录.的完整路径以NUL字节(0x0)结束.xargs -0通过NUL将stdin输入拆分为令牌 - 在这种情况下产生单个令牌,保留单个输入行的值 - 包含$PWD- 原样.这样做是安全的,因为NUL不是文件名中的合法字节.
-0是一个非标准扩展到了POSIX标准xargs,但它在这两个实施BSD xargs和GNU(上OSX为aused) xargs(在Linux所用).保持POSIX兼容[1],下一个最好的方法是使用带有选项的基于行的标记化,-I如下所示:printf '%s' "$PWD" | xargs -I % open %因此,实际上上述解决方案等同于(xargs最终执行的内容 - 请参阅下一节的解释):
open .
# Equivalent solution.
open "$PWD"
Run Code Online (Sandbox Code Playgroud)
[1] xarg的-I选项要求POSIX系统也符合XSI标准.如果有人能够向我解释实际意义上的含义,我将不胜感激.
B:为客户提供最好的答案与上技术没有任何限制使用:
open .
Run Code Online (Sandbox Code Playgroud)
open期望参数而不是stdin输入,并且.简洁且最有效地表示当前目录,从而导致open显示当前文件夹的内容Finder.
一个等效但更冗长的解决方案是传递特殊的shell变量$PWD,它始终包含当前目录的完整路径(用双引号引用,以便保护它免受shell扩展:
open "$PWD"
Run Code Online (Sandbox Code Playgroud)
男人打开:
-f Reads input from standard input and opens the results in the
default text editor. End input by sending EOF character (type
Control-D). Also useful for piping output to open and having
it open in the default text editor.
Run Code Online (Sandbox Code Playgroud)
相同手册,在"示例"下:
ls | open -f将'ls'命令的输出写入/ tmp中的文件,并在默认文本编辑器中打开该文件(由LaunchServices确定).
你可以这样做 pwd | open -f