Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash, weird variable scope when populating array with results

Tags:

I am parsing command output and putting results into array.

Works fine until exiting the inner loop - output array is empty.

declare -a KEYS

#-----------------------------------------------------------------------------#
get_keys()
{

# this extracts key NAMES from log in format "timestamp keycode"
$glue_dir/get_keys $ip | while read line; do
    echo line: $line
    set -- $line # $1 timestamp $2 keycode
    echo 1: $1 2: $2
    key=(`egrep "\\s$2$" "$glue_dir/keycodes"`) # tested for matching '40' against 401, 402 etc
    set -- $key # $1 key name $2 keycode
    KEYS+=("$1")
    echo key $1
    echo KEYS inside loop: "${KEYS[@]}"
done
    echo KEYS outside loop: "${KEYS[@]}"
}

The output when run agains two output lines:

line: 1270899320451 38
1: 1270899320451 2: 38
key UP
KEYS inside loop: UP
line: 1270899320956 40
1: 1270899320956 2: 40
key DOWN
KEYS inside loop: UP DOWN
KEYS outside loop:

I spent an hour trying to figure this out. Please help. ;-)

like image 341
Jakub Głazik Avatar asked Sep 30 '11 15:09

Jakub Głazik


People also ask

What are the most common types of variables in Bash?

Excluding the above example, the most common type of variable you'll find in Bash is arrays: The above example assigns both Linux Handbook and It's FOSS as the values for the name variable. How do you go about accessing each value though? If you run echo $name, you'll see that it prints the first value, Linux Handbook.

Why is there a space before a variable in Bash?

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter. Bash sees the space before “Geek” as an indication that a new command is starting.

How do I see the active environment variables in Bash?

To see the active environment variables in your Bash session, use this command: env | less If you scroll through the list, you might find some that would be useful to reference in your scripts.

Why are my variables in quotation marks in Bash?

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter. Here’s an example: site_name=How-To Geek. Bash sees the space before “Geek” as an indication that a new command is starting.


1 Answers

When you use a pipe (|) to pass your command output to while, your while loop runs in a subshell. When the loop ends, your subshell terminates and your variables will not be available outside your loop.

Use process substitution instead:

while read line; do
   # ...
done < <($glue_dir/get_keys $ip)
like image 197
Shawn Chin Avatar answered Sep 21 '22 22:09

Shawn Chin