Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to automate wget tar cd using word designators and word modifiers

Tags:

bash

shell

tar

wget

How 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 now

Bash 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
like image 443
caleban Avatar asked Oct 19 '25 16:10

caleban


1 Answers

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"
like image 153
Dennis Williamson Avatar answered Oct 22 '25 06:10

Dennis Williamson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!