bash脚本使用word指示符和单词修饰符自动化wget tar cd(bash script to automate wget tar cd using word designators and word modifiers)
如何使用单词指示符和单词修饰符或类似的东西使用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 nowBash 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 directoryHow can I automate the following with a bash shell script using word designators and word modifiers or something similar?
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#When I try something like the below I get errors because word designators and word modifiers don't appear to work the same way in bash scripts as they do in a shell:
Bash Shell Script Example 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 nowBash Shell Script Example 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"History substitution works at the command line. In a script, you can use parameter expansion.
#!/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"更多推荐
发布评论