I'm trying to create a Bash script that will extract the last parameter given from the command line into a variable to be used elsewhere. Here's the script I'm working on:
#!/bin/bash # compact - archive and compact file/folder(s) eval LAST=\$$# FILES="$@" NAME=$LAST # Usage - display usage if no parameters are given if [[ -z $NAME ]]; then echo "compact <file> <folder>... <compressed-name>.tar.gz" exit fi # Check if an archive name has been given if [[ -f $NAME ]]; then echo "File exists or you forgot to enter a filename. Exiting." exit fi tar -czvpf "$NAME".tar.gz $FILES
Since the first parameters could be of any number, I have to find a way to extract the last parameter, (e.g. compact file.a file.b file.d files-a-b-d.tar.gz). As it is now the archive name will be included in the files to compact. Is there a way to do this?
$* Stores all the arguments that were entered on the command line ($1 $2 ...). "$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).
Also Alt + . can be used to recall the last argument of any of the previous commands.
The variable $@ contains the value of all positional parameters, excluding $0. The variable $* is the same as $@, except when it is double-quoted.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
To remove the last item from the array you could use something like this:
#!/bin/bash length=$(($#-1)) array=${@:1:$length} echo $array
Even shorter way:
array=${@:1:$#-1}
But arays are a Bashism, try avoid using them :(.
This is how I do in my scripts
last=${@:$#} # last parameter other=${*%${!#}} # all parameters except the last
EDIT
According to some comments (see below), this solution is more portable than others.
Please read Michael Dimmitt's commentary for an explanation of how it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With