cal*_*ban 4 bash shell wget tar
如何使用单词指示符和单词修饰符或类似的东西通过 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#
Run Code Online (Sandbox Code Playgroud)
当我尝试类似下面的操作时,我会收到错误,因为单词指示符和单词修饰符在 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
历史替换在命令行中工作。在脚本中,您可以使用参数扩展。
#!/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"
Run Code Online (Sandbox Code Playgroud)