在SHELL BASH脚本中获取WHILE以外的变量

时间:2015-01-26 08:14:32

标签: mysql bash shell sh do-while

如何在SHELL脚本中的“while”之外回显变量x和y:

#!/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

当我运行这个脚本x和y回显空格时,当我在“while”操作符内部回显时它工作但是如何在外面变量?

1 个答案:

答案 0 :(得分:1)

不要使用管道来避免在脚本中创建子shell并使用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

使用管道时,子shell会被创建,子shell中创建的变量会在子shell退出后丢失。