2017-01-11 45 views
1

我用Automator创建了一个macOS服务,它实际上会将Finder中的每个文件附加到一个新的Thunderbird撰写窗口,并且只是一个简单的bash脚本。如何检测文件是否是macOS上bash脚本中的文件夹?

for f in "[email protected]" 
do 
     open -a /Applications/Thunderbird.app/ "$f" 
done 

此服务还可以用于任何文件夹,但肯定无法将文件夹附加到撰写窗口。但我现在的想法是让脚本检测文件是文档还是文件夹。如果它是一个文件,请附上它。如果它是一个文件夹,首先压缩它并附加它。在方式:

if file is folder than 
// zip compress folder 
// attach *.zip to Thunderbird compose window 
else // seems to be a document 
// attach document to Thunderbird compose window 

但我怎么检测,如果该文件是一个文件夹,压缩比它在bash脚本的zip文件?

+0

请参阅:'help test | less' – Cyrus

回答

0

此命令[ -f "$filename" ]将返回true的文件,而[ -d "$dirname" ]将用于目录返回true。

我会建议使用一个检查文件,因为你可能有东西既不是目录也不是文件。

0

我会这样来解决:

if [ -d "$fileDirectory" ]; then myCommandDirectories; 
elif [ -f "$fileDirectory" ]; then myCommandFiles; 
elif [ -z "$fileDirectory" ]; then myCommandEmptyArgument; 
else myCommandNotFileDirectory; fi 

在上面的代码中,语法,如果该参数是一个directoryif [ -d ... ]将考验,语法,如果该参数是一个fileif [ -f ... ]将考验,语法if [ -z ... ]会测试参数是否为unset或设置为empty string,如果参数不是这些参数,您仍然可以执行某个命令/脚本(例如myCommandNotFileDirectory的示例)。

注意:我包括检查空字符串,即使没被问对问题,因为这是一个“质量/错误”控制测试,我通常会做 - 变量"$fileDirectory"不应该是空的在这种情况下,如果是的话,我想知道(它会告诉我脚本不能正常工作),因此我通常会将该命令重定向到日志文件,如下所示:

elif [ -z "$fileDirectory" ]; then somecommand && echo "empty fileDirectory string ocurred" >> /var/log/mylog; 
2

代码:

#!/bin/bash 
if [ -d "$f" ]; then 
    upload_file="$f.zip" 
    # zip compress folder 
    zip "$f.zip" "$f" 
elif [ -f "$f" ]; then # seems to be a document 
    upload_file="$f.zip" 
else # Unknown file type 
    echo "Unknown file type." 1>&2 
    exit 1 
fi 
# attach file to Thunderbird compose window 
open -a /Applications/Thunderbird.app/ "$upload_file" 
exit 0 

说明:
在bash中“文件夹”被称为“目录”。您应该检查测试的手册页。

$ man test 

对您的相关部分是:

NAME 
test, [ -- condition evaluation utility 

SYNOPSIS 
test expression 
[ expression ] 

...

-d file  True if file exists and is a directory. 

-e file  True if file exists (regardless of type). 

-f file  True if file exists and is a regular file. 

测试如果文件是目录:

test -d "$f" 

OR

[ -d "$f" ] 

要测试如果一个文件是一个普通文件:

test -f "$f" 

OR

[ -f "$f" ] 

编辑:在示例代码中引用变量以避免通配符和分词。

相关问题