Reputation: 11
Say that I want to make a script that extracts all tar.gz and tar.bz2 files that are listed as arguments. What I've done so far is something like:
if [[ $@ =~ .*"tar.gz".* ]] || [[ $@ =~ .*"tar.bz2".* ]]; then
for i in $@ =~ .*"tar.gz".*; do
tar -xvzf "$i"
done
for p in $@ =~ .*"tar.bz2".*; do
tar -xvjf "$p"
done
else
echo "tar.gz or tar.bz2 files required."
fi
The first line is successful at evaluating whether or not a tar.gz or tar.bz2 file exist, but my problem is the rest. The variables aren't set properly, and the script ends up trying to extract each variable listed with both extraction commands. How can I separate arguments that end with tar.gz and tar.bz2 to perform separate extractions?
Upvotes: 0
Views: 89
Reputation: 6995
You should probably iterate over arguments and test each argument, like this :
#!/bin/bash
declare -i count
for file in "$@"
do
if
[[ $file =~ .*[.]tar[.]gz$ ]]
then
tar -xvzf "$file"
elif
[[ $file =~ .*[.]tar[.]bz2$ ]]
then
tar -xvjf "$file"
else
continue
fi
count+=1
fi
((count)) || echo "tar.gz or tar.bz2 files required."
If you are OK to rely on GNU tar
choosing the right decoding algorithm automatically, you can simplify this to :
#!/bin/bash
declare -i count
for file in "$@"
do
[[ $file =~ .*[.]tar[.](gz|bz2)$ ]] || continue
tar -xvf "$file"
count+=1
fi
((count)) || echo "tar.gz or tar.bz2 files required."
Upvotes: 3
Reputation: 136246
A bit off-topic, when extracting with GNU tar it detects the archive type automatically from the file extension since 2007, no need to specify z|j|J
.
I.e. tar xvf <filename>
.
Upvotes: 0
Reputation: 295373
There isn't any built-in syntax for extracting and iterating over only matching elements of an array, as you're trying to do here.
The below is POSIX-compliant, depending on no bashisms:
count=0
for arg; do
case $arg in
*.tar.gz) tar -xvzf "$arg"; count=$(( count + 1 ));;
*.tar.bz2) tar -xjvf "$arg"; count=$(( count + 1 ));;
esac
done
if [ "$count" -eq 0 ]; then
echo "tar.gz or tar.bz2 files required" >&2
fi
Upvotes: 3