Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract parameters before last parameter in "$@"

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?

like image 446
user148813 Avatar asked Aug 01 '09 01:08

user148813


People also ask

What is difference between $@ and $*?

$* 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" ...).

What command brings back the arguments and options from the previous line?

Also Alt + . can be used to recall the last argument of any of the previous commands.

What is the difference between the two positional parameters $@ and $*?

The variable $@ contains the value of all positional parameters, excluding $0. The variable $* is the same as $@, except when it is double-quoted.

What is $@ in bash?

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.


2 Answers

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 :(.

like image 75
Krzysztof Klimonda Avatar answered Sep 17 '22 18:09

Krzysztof Klimonda


Portable and compact solutions

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.

like image 20
ePi272314 Avatar answered Sep 17 '22 18:09

ePi272314