如何在Mac上编写一个BASH脚本来下载和解压文件?

29

我需要创建一个可以在Mac电脑上使用的Bash脚本,它需要下载一个网站的ZIP文件并将其解压到特定位置。

  1. 下载ZIP文件 (curl -O)
  2. 将文件解压到指定位置 (unzip 文件名.zip 保存路径)
  3. 删除.zip文件

我需要让用户可以双击桌面上的文本文件,它会自动在终端中运行。

如何使用户可以双击桌面上的图标并运行脚本?该文件需要什么扩展名?


2
文件需要一个.cmd扩展名。 - the Tin Man
curl -L http://example.org/file.zip | bsdtar -xvf - -C /path/to/save - davidcondrey
3个回答

42

OSX 使用与 Linux 相同的 GNU sh/bash。

#!/bin/sh

mkdir /tmp/some_tmp_dir                         && \
cd /tmp/some_tmp_dir                            && \
curl -sS http://foo.bar/filename.zip > file.zip && \
unzip file.zip                                  && \
rm file.zip

第一行的 #!/bin/sh 被称为"shebang"行,是强制性的。


2
默认情况下,Mac OS 中没有安装 wget。但是有安装 curl - the Tin Man
5
可以将curl的结果直接传输到unzip而不创建file.zip文件吗? - pogibas
如果你喜欢看到进度,请不要使用静默的-sS标志。 - Aras
在文件开头添加 set -e,并在 curl 命令中添加 --fail,如果您希望脚本在无法下载文件时退出。 - Joscha
对于Bash来说,在行末加上&&就足够了,不需要使用反斜杠。 - ceving

16

BSD Tar可以通过流打开zip文件并进行解压缩。-L或--location标志用于跟随重定向。因此,以下命令将起作用:


BSD Tar 可以打开 zip 文件并使用流进行解压缩。 -L 或 --location 标志用于跟踪重定向。所以下面的命令可以工作:
curl --show-error --location http://example.org/file.zip | tar -xf - -C path/to/save

8
文件必须是tar文件,否则会出现“tar: This does not look like a tar archive”的错误提示。 - Anthony Hatzopoulos
1
它在 Mac 上对 tar 有效,但在 Linux 上会出错。 - Slavik
1
我刚意识到我重复了这个答案。对于我来说,它在Mac和Linux上都可以工作。你可能遇到了重定向并且没有按照-L参数进行操作。尝试使用curl -SL https://www.sample-videos.com/zip/10mb.zip | tar -xz - -C . - lauksas
你能看得懂吗?这是关于ZIP文件,不是TAR文件。 - iirekm
@iirekm,你能看到“BSD Tar”(使用libarchive)可以打开zip文件。 ;) - ruario
从我的Linux Mint运行时,出现错误 > tar: 这看起来不像是一个tar归档文件 tar: 跳过到下一个头部 - undefined

8
如果您不想改变目录上下文,请使用以下脚本:
```html

如果您不想改变目录上下文,请使用以下脚本:

```
#!/bin/bash

unzip-from-link() {
 local download_link=$1; shift || return 1
 local temporary_dir

 temporary_dir=$(mktemp -d) \
 && curl -LO "${download_link:-}" \
 && unzip -d "$temporary_dir" \*.zip \
 && rm -rf \*.zip \
 && mv "$temporary_dir"/* ${1:-"$HOME/Downloads"} \
 && rm -rf $temporary_dir
}

使用方法:

# Either launch a new terminal and copy `git-remote-url` into the current shell process, 
# or create a shell script and add it to the PATH to enable command invocation with bash.

# Place zip contents into '~/Downloads' folder (default)
unzip-from-link "http://example.com/file.zip"

# Specify target directory
unzip-from-link "http://example.com/file.zip" "/your/path/here"

输出:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 17.8M  100 17.8M    0     0  22.6M      0 --:--:-- --:--:-- --:--:-- 22.6M
Archive:  file.zip
  inflating: /tmp/tmp.R5KFNvgYxr/binary

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接