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

Re: Help with awk

Les Mikesell <lesmikesell gmail com> wrote:

aragonx dcsnow com wrote:
> I bet awk has it's own user list but before I go and subscribe to another
> one, I figured I would ask here first.  I have the following awk code that
> is trying to set a variable of the shell it is running in.  It doesn't
> work and I've searched high and low to see how to get it to do so.
> > The reason I don't just use DOMAIN= 'awk blah blah blah' is I want to set
> more than one shell variable for each record.  But I have to get this
> working first. :( > > #!/bin/bash > > awk '{FS=":"}{system ("DOMAIN=" $1); }
>         {system ("DOMAIN="$1)};
>         {system ("echo \"$DOMAIN\"")};
> ' /etc/passwd
> > Any help would be appreciated.

This isn't an awk question, it's a 'how unix works' question. A child process can't change anything in it's parent's environment. Your awk program will be a child of the shell running it; the system statements run yet another shell as a child under awk. All of those processes have their environment strings in protected memory (inherited shared but copy-on-write).

The var=`command ..` will work, or you can do all of the work that needs the setting in the lowest level subprocess that has the right values.

-- Les Mikesell lesmikesell gmail com
An alternative is to have the awk script output the shell commands you want. That is, change your {system ("DOMAIN="...} to a print statement. You then execute the command created by your awk script in the calling shell's environment. Something along the lines of:

foo = `awk '{FS=":"}{printf "export DOMAIN=%s\n", $1}' < /etc/passwd`
`echo $foo`

After the above, $DOMAIN should have the value you want for the *last entry* in /etc/passwd. Not sure if this is what you really want. That may be:

foo=`awk 'BEGIN {FS=":"} $1 ~ /'$USER'/ {printf "export DOMAIN=%s\n", $1}' /etc/passwd`
`echo $foo`

You'll find understanding quoting and order of execution is really useful when writing this kind of shell script. ;-)


Politics, n. Strife of interests masquerading as a contest of principles.
-- Ambrose Bierce

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