Reputation: 1523
i have a little and probably very stupid problem..
I'm trying to make an alias for tar and gzip which uses the file name (given as an argument), but it is not converting as expected to the filename in the output.
My alias is:
alias targz='tar -cvzf $1.tar.gz $1'
It works, but the argument stored in $1 is not working when setting the filename, it zips it in a file called ".tar.gz".
I tried just echoing '$1.tar.gz' and the output is '.tar.gz', so, i think it should be something very stupid in the format.
Any help is welcome,
Upvotes: 1
Views: 5033
Reputation: 60058
Aliases don't have positional parameters. They're basically macros (an alias gets replaced with the text of the alias when executed).
You could use a function:
targz() {
tar -cvzf "$1".tar.gz "$1"
}
or a script
#!/bin/bash
tar -cvzf "$1".tar.gz "$1"
Personally, I've been using something like the following script to achieve a similar goal (comments added for your convenience):
#!/bin/bash
#support multiple args
for arg in "$@"
do
#strip ending slash if present (tab-completion adds them)
arg=${arg%/}
#compress with pigz (faster on multicore systems)
tar c "$arg" | pigz - > "$arg".tgz
done
In case you want my complete version, I also remove the argument directory if the tarring and compression succeed (similar to what gzip does for individual files)
#!/bin/bash
set -o pipefail
for arg in "$@"
do
arg=${arg%/}
tar c "$arg" | pigz - > "$arg".tgz && rm -rf "$arg"
done
Update: Credits to @mklement0 for the more succinct and more efficient stripping of ending slashes.
Upvotes: 4
Reputation: 206
Try to make a script to do that, like this.
echo """
#!/bin/bash if [ -z $1 ]; then
echo "Variable is Null"
else
tar -cvzf $1.tar.gz $1
fi
""" > /usr/local/bin/targz
chmod +x /usr/local/bin/targz
Upvotes: 0
Reputation: 16039
Use an alias to a function for it, something like:
alias targz='function targz_() { tar -cvzf "$1.tar.gz" "$1"; return 0; }; targz_ '
Upvotes: 1