2015-04-05 59 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

相關問題