如何使用单词指示符和单词修饰符或类似的东西使用 bash shell 脚本自动执行以下操作?
root@server:/tmp# wget -q http://download.zeromq.org/zeromq-2.2.0.tar.gz
root@server:/tmp# tar -xzf !$:t
tar -xzf zeromq-2.2.0.tar.gz
root@server:/tmp# cd !$:r:r
cd zeromq-2.2.0
root@server:/tmp/zeromq-2.2.0#
当我尝试如下操作时,我收到错误,因为单词指示符和单词修饰符在 bash 脚本中的工作方式似乎与在 shell 中的工作方式不同:
Bash Shell 脚本示例 1:
#!/usr/bin/env bash
wget -q http://download.zeromq.org/zeromq-2.2.0.tar.gz && tar -xzf !$:t && cd !$:r:r
root@server:/tmp# ./install.sh
tar (child): Cannot connect to !$: resolve failed
gzip: stdin: unexpected end of file
tar: Child returned status 128
tar: Error is not recoverable: exiting now
Bash Shell 脚本示例 2:
#!/usr/bin/env bash
wget -q http://download.zeromq.org/zeromq-2.2.0.tar.gz
tar -xzf !$:t
cd !$:r:r
root@server:/tmp# ./install.sh
tar (child): Cannot connect to !$: resolve failed
gzip: stdin: unexpected end of file
tar: Child returned status 128
tar: Error is not recoverable: exiting now
./install.sh: line 11: cd: !$:r:r: No such file or directory
历史记录替换在命令行中工作。在脚本中,可以使用参数扩展。
#!/usr/bin/env bash
url=http://download.zeromq.org/zeromq-2.2.0.tar.gz
wget -q "$url"
tarfile=${url##*/} # strip off the part before the last slash
tar -xzf "$tarfile"
dir=${tarfile%.tar.gz} # strip off ".tar.gz"
cd "$dir"
如果提供的示例是您尝试解决的唯一问题,也许以下内容会有所帮助:
version="2.2.0"
wget -q http://download.zeromq.org/zeromq-${version}.tar.gz
tar -xzf zeromq-${version}.tar.gz
cd zeromq-${version}
在 bash 脚本中,版本可能是传递给脚本的第一个选项:
version=$1
这不包含错误处理等,但应该可以帮助您入门。