[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Possible Feature Requests (unsource, exchange)

From: Greg Wooledge
Subject: Re: Possible Feature Requests (unsource, exchange)
Date: Tue, 7 Jul 2009 14:37:20 -0400
User-agent: Mutt/

On Tue, Jul 07, 2009 at 08:16:50PM +0200, Christopher Roy Bratusek wrote:
> unsource: the opposite of source (while source is making functions
> publically available, unsource would remove them) 

You can "unset -f" a function.  You could source a script-file that
contains a bunch of "unset -f foo" commands.

If what you want is "parse the bash commands in a script-file and do
the opposite of every one that sets a variable", that's probably

> exchange: exchanges the value of two variables (x=2 y=a; exchange x y;
> x=a y=2 -- need to be exported, so $1 $2 inside a function/script don't
> help that much)

A function would not impair you here.  Functions are executed in the
same process as the caller, as long as you don't do anything else
that would create a subshell.

# Usage: exchange varname1 varname2
exchange() {
   local tmp
   [[ $1 = *[^[:alnum:]_]* || $1 = [0-9]* ]] &&
     { echo "Naughty naughty" >&2; return 1; }
   [[ $2 = *[^[:alnum:]_]* || $2 = [0-9]* ]] &&
     { echo "Naughty naughty" >&2; return 1; }
   eval tmp=\$$1
   eval $1=\$$2
   eval $2=\$tmp
   return 0

Note: while I did test this, and while I did intend it to be safe, you
should double-check it yourself before relying on it.  Eval is a very
sharp knife.

> echo no-expand: if you do echo $@ ($@ is $x $y for example) echo will
> print the values of $x $y instead of simply $x and $y is there a way to
> achieve this?

Quoting error.  If you want to print the contents of the string consisting
of all the positional parameters with a single space in between each
pair, then use one of these:

echo "$*"
echo "$@"
printf "%s\n" "$*"           # pretty safe; but still IFS-sensitive
x="$@"; printf "%s\n" "$x"   # I think this one's totally safe....

Or with a single space after each one and then a trailing newline:

print "%s " "$@"; echo       # very safe but has extra trailing space

Also, your original statement of the problem was wrong:

imadev:~$ set -- '$x' '$y'; x=1 y=2
imadev:~$ echo $@
$x $y

I think your actual problem was that you had globbing characters in
the positional parameters, not dollar signs:

imadev:~$ set -- 'foo*' '$y'; x=1 y=2
imadev:~$ echo $@
foo foo1 foo-s foo.c foo.conf foo.cpp foo.gif foo.ini foo.m4 foo.new foo.pl 
foo.sh foo.tar.gz foo.tcl $y

If you insist on not quoting things (a practice which I would not
recommend you pick up unless it's absolutely required for a particular
script), then you can use "set -f" to suppress the glob expansion.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]