1

How echo variable x and y outside "while" in SHELL script:

#!/bin/bash
x=1
y=1

    mysql -e "show tables like 'do97_%';" --host=localhost --skip-column-names -u login999il --password=e9999999999df54y basenamel | while read tables; do
    mysql -e "SELECT id, tolbox, del_time FROM $tables WHERE deleted=0 ORDER BY create_time DESC LIMIT 0" --host=localhost --skip-column-names -u login999il --password=e9999999999df54y basenamel | while read id tolbox del_time; do
    y=$(($y+1))

    done

    x=$(($x+1))
    done

    # how get this variable outside "WHILE"
    echo $x
    echo $y

when I run this script x and y echo empty space, when i echo this inside "while" operator it work but how get variable outside?

snex
  • 982
  • 11
  • 21
  • 1
    This has been answered so many times.First result on google http://stackoverflow.com/questions/4667509/problem-accessing-a-global-variable-from-within-a-while-loop –  Jan 26 '15 at 08:49

1 Answers1

1

Don't use pipe to avoid a subshell being created in your script and use process substitution:

#!/bin/bash

x=1
y=1

while read -r tables; do

    while read -r id tolbox del_time; do
       ((y++))    
    done < <(mysql -e "SELECT id, tolbox, del_time FROM $tables WHERE deleted=0 ORDER BY create_time DESC LIMIT 0" --host=localhost --skip-column-names -u login999il --password=e9999999999df54y basenamel)

    ((x++))
done < <(mysql -e "show tables like 'do97_%';" --host=localhost --skip-column-names -u login999il --password=e9999999999df54y basenamel)

# now get this variable outside "WHILE"
echo $x
echo $y

While using a pipe a subshell gets created and variables created in subshell get lost after subshell exits.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • `line 98: syntax error near unexpected token `<' line 98: `done < <(mysql -e "SELECT id, tolbox, del_time FROM $tables WHERE deleted=0 ORDER BY create_time DESC LIMIT 0" --host=localhost --skip-column-names -u login999il --password=e9999999999df54y basenamel)' ` my bash not support process substitution? – snex Jan 26 '15 at 11:40
  • All BASH versions support it. Check you version by using `bash --version` command – anubhava Jan 26 '15 at 11:43
  • GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software; you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. – snex Jan 26 '15 at 11:44
  • Absolutely supported in BASH 4+ make sure you execute it via `bash ./script.sh` command – anubhava Jan 26 '15 at 11:45