[英]How to detect if a file is a folder in bash script on macOS?
我使用Automator创建了一个macOS服务,该服务实际上会将来自Finder的每个文件附加到新的Thunderbird撰写窗口,并且仅仅是一个简单的bash脚本。
for f in "$@"
do
open -a /Applications/Thunderbird.app/ "$f"
done
该服务也适用于任何文件夹,但是请确保您不能将文件夹附加到撰写窗口。 但是我现在的想法是让脚本检测文件是文档还是文件夹。 如果是文档,请附加它。 如果是文件夹,请先用zip压缩后再附加。 方式:
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文件呢?
if [[ -d "$file" ]]; then
# do your thing for the directory
else
# do the other thing for the file
fi
有关更多详细信息,请参见以下相关问题: 如何确定Bash中是否不存在常规文件?
码:
#!/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"
要么
[ -d "$f" ]
要测试文件是否为常规文件:
test -f "$f"
要么
[ -f "$f" ]
编辑:示例代码中带引号的变量,以避免出现乱码和单词拆分。
此命令[ -f "$filename" ]
对于文件将返回true,而[ -d "$dirname" ]
对于目录将返回true。
我建议也使用文件检查,因为您可能既不是目录也不是文件。
我会这样处理:
if [ -d "$fileDirectory" ]; then myCommandDirectories;
elif [ -f "$fileDirectory" ]; then myCommandFiles;
elif [ -z "$fileDirectory" ]; then myCommandEmptyArgument;
else myCommandNotFileDirectory; fi
在上面的代码中, if [ -d ... ]
的语法将测试该参数是否为directory
, if [ -f ... ]
的语法将测试该参数是否为file
, if [ -z ... ]
将测试是否未unset
参数或将其设置为empty string
,并且如果参数都不为empty string
,则仍可以执行某些命令/脚本(在myCommandNotFileDirectory
上方的myCommandNotFileDirectory
)。
注意 :我包括检查一个空字符串,即使没有问这个问题也是如此,因为这是我通常会进行的“质量/错误”控制测试-变量"$fileDirectory"
在此情况下永远不应为空,如果是的话,我想知道(它会告诉我脚本不能正常工作),因此通常我会将命令重定向到日志文件,如下所示:
elif [ -z "$fileDirectory" ]; then somecommand && echo "empty fileDirectory string ocurred" >> /var/log/mylog;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.