bash - 压缩 I/O 错误 : No such file or directory in bash script

标签 bash macos zip

我一直在编写一些代码来(主要)自动化密码保护和压缩/归档文件夹和文件。但是,代码似乎讨厌我。

我已经逐行运行它,它总是在 zip 命令上阻塞,即使 $file$source是正确和有效的。

有任何想法吗?

这是源代码:

#!/bin/bash
echo "Drag in the source file"
read source
echo

echo "Drag in the destination file, or press enter to select the Desktop"
read destination
echo

if [ -z "$destination" ]
then destination="$PWD/Desktop"
echo "Destination is set to the desktop"
fi

echo "Type the name of the file to make"
read file

if [ -z "$file" ]
then file="archive"
echo "File name set to archive.zip"
fi

file="${destination}/${file}"

if [ -d $"source" ]
then zip -erj "$file" "$destination"
else zip -ej "$file" "$destination"
fi

最佳答案

您的代码中有几个问题:

if [ -z "$destination" ]
then destination="$PWD/Desktop"
echo "Destination is set to the desktop"
fi
$PWD是当前工作目录。当您打开终端时,它是您的主目录,但每次运行时它都会更改 cd .

桌面目录是 $HOME/Desktop .

如果你不从你的主目录运行脚本,很可能是 $PWD/Desktop不存在,这是导致错误的原因; zip不会尝试为您要求它构建的存档创建目标目录。如果该目录尚不存在,则会显示一条错误消息并退出。

另一个问题是调用 zip :
if [ -d $"source" ]
then zip -erj "$file" "$destination"
else zip -ej "$file" "$destination"
fi

您可能想要归档文件 $source$source 中的文件目录(如果是目录)但您错误地输入了$destination作为要在 zip 中存档的文件/目录命令行。
if [ -d $"source" ] -- 应该是"$source" , 否则报价无用,如果 $source包含空格脚本将退出并出现语法错误。

最后一件事:zip不介意接收-r在命令行中,当它被要求只归档一个文件时。您可以替换整个 if/else用一个命令阻止上面的:
zip -erj "$file" "$source"

关于bash - 压缩 I/O 错误 : No such file or directory in bash script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43036133/

相关文章:

linux - Bash 脚本启动程序并在给定时间退出

linux - ssh 连接到另一台服务器上的用户并以该用户身份执行 shell 命令

html - 无法在 chrome(mac)中打开某些 html 文件

c++ - 自动卸载 OS X 驱动程序

python - 分隔 (X,Y) 列表

linux - 以 root 身份运行 bash 安装脚本 - 如何处理普通用户的文件?

python - 在Python中,应该如何测试环境变量中指定的路径中是否存在文件?

ruby-on-rails - 如何在没有文档的情况下安装 Rails?

python - 监控 ZIP 文件提取 Python

java - 是否可以组合 ZipOutputStream 和 DigestOutputstream?