繁体   English   中英

如何编写 BASH 脚本以在 Mac 上下载和解压缩文件?

[英]How do I write a BASH script to download and unzip file on a Mac?

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

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

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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM