2015-04-05 66 views
0

我想用osx open命令打开一个文件,但是我拥有的是一个包含文件名(和路径)而不是文件名本身的变量。 我想:bash osx通过变量或管道打开文件

thisfile=./filename.extension 
open $thisfile 

thisfile=./filename.extension 
printf $thisfile | open 

printf ./filename.extension | open 

但在所有这些尝试的我只是得到

Usage: open [-e] [-t] [-f] [-W] [-R] [-n] [-g] [-h] [-b <bundle identifier>] [-a <application>] [filenames] [--args arguments] 
Help: Open opens files from a shell. 

...(全文: http://pastie.org/10074666

我在做什么错?如何通过管道和变量打开文件?


EDIT /溶液:

我确实有空间(和括号),我在变量存储之前\逃脱。事实证明,我不应该这样做,我应该通过变量使用open "${thisfile}"open $thisfile

所以对于文件

./foo - moo/zoo - boo (100)/poo (too).jpg 

与开开这样

thisfile='./foo - moo/zoo - boo (100)/poo (too).jpg' 
open "${thisfile}" 
+0

你的文件名是否有空格?你是否得到'无效选项:xxx'? – zmo 2015-04-05 09:12:05

+2

您的第一个命令适用于OSX Yosemite。我不认为其他2将工作,因为'open'不读取它的'stdin',而是使用一个参数。 – 2015-04-05 09:17:05

+0

如果你的文件名中有空格,使用'thisfile =“名称加空格”',并打开$ thisfile“' – 2015-04-05 09:39:52

回答

1

作为@标记瑟特查对它进行了评论,open对stdin没有任何要求。所以让我们来了解第一种情况会出现什么问题。

当您尝试使用OSX上的open命令打开一个文件时,我看到三个主要方案:

①该文件不存在或有空格:

% open doesnotexists 
The file /path/to/doesnotexists does not exist. 
Usage: … 
% open has spaces 
The files /path/to/has and /path/to/pyodsdiff/spaces do not exist. 
Usage: … 

②该文件包含破折号:

% open -notanoption 
open: invalid option -- n 
Usage: … 
% open --notanoption 
open: invalid option `--notanoption' 
Usage: … 

③变量包含什么:

% open 
Usage: … 

所以,它看起来像③!即:但是你声明你的变量,你没有做到这一点。

要测试你如何声明您的变量,只需使用echo代替open

% thisfile=README.md echo $thisfile 

% thisfile=README.md 
% echo $thisfile 
README.md 
% thisotherfile=README.md ; echo $thisotherfile 
README.md 
+0

非常有帮助esp,因为我看不到返回的特定错误(只是http://pastie.org/10074666)。我的实际文件看起来像'./foo - moo/zoo - boo(100)/ poo(too).jpg'我一直在尝试执行'$'thisfile ='。/ foo \ - \ moo/zoo \ - \ boo \\(100 \)/ poo \\(too \)。jpg'' then'$ open $ thisfile'当我不应该打扰转义空格和(),并使用'$ open“$ {thisfile} “'我不确定它是否是最优雅的解决方案,但它确实有效。如果您知道在管道中使用**打开**的方法,请随时添加,同时我会尝试此http://unix.stackexchange.com/questions/49019 – okapiho 2015-04-05 10:31:20

+1

您可以使用输出的命令来填充一个变量:'MYVAR = $(find。-name'README.md');打开$(MYVAR)''这可能会打开多个文件,路径有_no spaces_,或使用'MYVAR = $(find。-name'README.md');打开“$(MYVAR)”'如果有空格。如果你的文件路径中有多个文件和空格,你可能需要使用find的-exec选项,或者使用'OLDIFS = $ IFS; IFS = $'\ n'; for $ MYVAR;打开“$ f”;完成; IFS = $ OLDIFS'。 – zmo 2015-04-05 11:25:20

1

如果你换行一个名为filelist变量分隔的文件名,那么我认为你需要做这样的事情这个:

echo -e $filelist | while IFS=$'\n' read f; do open "$f"; done 
+0

这样做的好处是可以单独打开每个文件,这些文件在发送到Preview.app时很重要(尽管我意识到我既没有指定多个文件,也没有需要在我的原始问题中单独打开或一起打开它们)。我想补充一点,我可以通过将'filelist'作为一个文件并在bash4中填充一个数组,每个元素一行,然后打开$ {array [@]}“来打开它们,类似于: http://unix.stackexchange.com/a/174117 – okapiho 2015-04-05 13:48:29