Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

bash: saving the positional parameters

7 views
Skip to first unread message

Glenn Morris

unread,
Jul 14, 2003, 3:13:17 PM7/14/03
to

How does one save the positional parameters to another variable in
bash, in such a way that whitespace is preserved correctly?

As an example of my problem:

#!/bin/bash

set -- "a b" "c d"
touch "$@"

ls -l "$@"

## I would like to save the positional parameters in a new variable x,
## then use $x exactly as per "$@".
## However, all these combinations fail.
x="$@"; ls -l $x
x="$@"; ls -l "$x"
x=$@; ls -l $x
x=$@; ls -l "$x"


The motivation for this is that I want to use the change of IFS +
redefinition of the positional parameters approach to process some
other variable (a la Bash FAQ E4). After this is done, I want to
restore the positional parameters to their original values.

Thanks in advance for any help.

Moshe Jacobson

unread,
Jul 14, 2003, 3:24:22 PM7/14/03
to
Glenn Morris had nothing better to do than to say:

> ## I would like to save the positional parameters in a new variable x,
> ## then use $x exactly as per "$@".
> ## However, all these combinations fail.
> x="$@"; ls -l $x
> x="$@"; ls -l "$x"
> x=$@; ls -l $x
> x=$@; ls -l "$x"

$@ is a special variable when quoted. No other variable will behave
the same way from inside quotes. So what you must do is store them in
an array:

params=("$@") # To store the parameters

set -- "${params[@]}" # To restore the params

Hope that helps,

Moshe

--
*** SPAM BLOCK: Remove bra before replying! ***
Moshe Jacobson :: http://runslinux.net :: moshe at runslinux dot net
!! FBI Arreseting Programmers? http://www.freesklyarov.org
!! Trust Microsoft Anti-Trust: http://www.anti-dmca.org

Stephane CHAZELAS

unread,
Jul 14, 2003, 3:27:08 PM7/14/03
to
Glenn Morris wrote:
>
> How does one save the positional parameters to another variable in
> bash, in such a way that whitespace is preserved correctly?
>
> As an example of my problem:
>
> #!/bin/bash
>
> set -- "a b" "c d"

In bash, use arrays:

saved_args=( "$@" )
and to restore:
set -- "${saved_args[@]}"

With Bourne or POSIX shells:

saved_args=
for i
do
saved_args=$saved_args\ \'`sed -e "
s/'/'\\\\\\\\''/g;\\\$s/\\\$/'/" << EOF
$i
EOF
`
done

and to restore:

eval set x "$saved_args"
shift

--
Stéphane

Glenn Morris

unread,
Jul 14, 2003, 7:37:57 PM7/14/03
to

Thank you Stéphane and Moshe for your quick and helpful replies -
much appreciated.
0 new messages