-   Programming (
-   -   bash arguments (

stuckinhell 08-12-2004 07:42 PM

bash arguments
I have a bash script where the last argument is a non-quoted path. THerefore, there can be a space in it. I would like to assign this path to a variable in my bash script but of course, if there's a space in there, the script considers it as a separate argument.
Is there a way for me to say

var2=(everything after the first argument passed to the bash shell)

e.g. if the name of the bash shell is, when i run arg1 /opt/my software/run

I would like for var2 to have the value /opt/my software/run


ilikejam 08-12-2004 08:45 PM

You'll have to 'escape' the space when you call the script.

E.g. arg1 /opt/my\ software/run

Or, if the script should only ever have two arguments, you could join any arguments after the first inside the script. I think just escaping the space when you call the script is easier. If you use tab completion, bash will probably add the '\' for you.


stuckinhell 08-12-2004 09:25 PM

I'd like to join the arguments inside the script...but how do i do that?Thanks...

ilikejam 08-12-2004 10:00 PM

Something along the lines of:



for go in $*
    if [ $go != $1 ]
        ARG2="$ARG2 $go"

That will give you the second argument in $ARG2


jschiwal 08-12-2004 10:27 PM

You may want to play with example 9.6 on this webpage tutorial.
It explains the difference between "$*" and "$@".

The argument separation characters are defined by the $IFS variable which you can change in your script. Also the "$*" argument refers to the entire argument list as an entire word, starting with the command itself.

Your best bet is to be consistent with all other commands and either quote the argument, or escape the space with a backslash when entering the argument.

Also, put quotes around variables in scripts that expand into filenames.
for example in this line
for file in *.JPG; do mv "${file}" "${file%.JPG}.jpg"; done
the quotes are necessary around ${file} if a file might possible contain a separation character.

ilikejam 08-12-2004 10:56 PM

I stand corrected. I've been using $* wrong all this time. This could explain some strangeness in some stuff I was working on a while ago.

Cheers for the link jschiwal.


Hko 08-13-2004 05:10 AM


Originally posted by stuckinhell
I'd like to join the arguments inside the script...but how do i do that?Thanks...
It had already been said, but also IMO it's really better to just pass the path parameter quoted, and if not that, at least have the space(s) escaped with a backslash.

But if you want to do it anyways:



echo "First argument is: $ARG1"
echo "The path argument is: $ARGPATH"

Note: this will fail when there are more than one spaces in a row, for example:

bash$ ./ arg1 /opt/my              software/run

All times are GMT -5. The time now is 05:36 AM.