【问题标题】:How do I write a BASH script to download and unzip file on a Mac?如何编写 BASH 脚本以在 Mac 上下载和解压缩文件?
【发布时间】:2012-01-23 08:08:58
【问题描述】:

我需要创建一个可以在 mac 上运行的 bash 脚本。它需要下载一个站点的 ZIP 文件并将其解压缩到特定位置。

  1. 下载 ZIP 文件 (curl -O)
  2. 将文件解压缩到特定位置 (unzip filename.zip path/to/save)
  3. 删除 .zip 文件

我需要这样做,以便人们可以双击桌面上的文本文件,它会自动在终端中运行。

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

【问题讨论】:

  • 文件需要.cmd扩展名。
  • curl -L http://example.org/file.zip | bsdtar -xvf - -C /path/to/save

标签: bash macos unzip


【解决方案1】:

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”行,是强制性的

【讨论】:

  • 默认情况下,wget 未安装在 Mac OS 中。 curl 是。
  • 是否可以在不创建 file.zip 的情况下直接通过管道将 curl 结果解压缩?
  • 如果您希望看到进度,请不要使用静音-sS 标志
  • 在文件的开头添加set -e--fail 如果您希望脚本在文件无法下载时退出。
  • 对于 Bash,使用 && 终止该行就足够了。反斜杠不是必需的。
【解决方案2】:

BSD Tar 可以打开一个 zip 文件并通过流解压缩。-L 或 --location 标志用于跟随重定向。所以以下将起作用:

curl --show-error --location http://example.org/file.zip | tar -xf - -C path/to/save

【讨论】:

  • 文件必须是 tar 文件,否则 tar: This does not look like a tar archive
  • 它适用于 Mac 上的 tar,但在 Linux 上会出错
  • 我刚刚意识到重复了这个答案。它适用于我的mac和linux。你可能有一个重定向,而不是 -L 参数。试试curl -SL https://www.sample-videos.com/zip/10mb.zip | tar -xz - -C .
【解决方案3】:

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

#!/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

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多