【问题标题】:How do I extract multiple MySQL columns to an environment variable in a shell script?如何在 shell 脚本中将多个 MySQL 列提取到环境变量中?
【发布时间】:2011-10-16 07:36:24
【问题描述】:

我想将表格中的一些数据提取到 shell 脚本中的变量中。现在我做这样的事情:

export NAME=`mysql -NB -e "select name from user where id = $ID"`
export AGE=`mysql -NB -e "select age from user where id = $ID"`
export LOCATION=`mysql -NB -e "select location from user where id = $ID"`

这很好用,但我希望在一个查询中完成所有操作,例如:

select name, age, location from user where id = $ID

我尝试像这样使用“读取”:

mysql -NB -e "select name, age, location from user where id = $ID" | read NAME AGE LOCATION
echo $NAME

...但它没有像我预期的那样工作(“echo”行没有输出)。我错过了什么吗?

【问题讨论】:

    标签: mysql bash shell


    【解决方案1】:

    如果您在管道中使用read,它将创建一个子shell 并在此子shell 中设置一个变量,该变量不会影响父shell(您工作的地方)。 一个想法:

    export IFS=. ; set -- $(mysql -N "select CONCAT_WS('.',name,age,location) from user where id=$ID")
    NAME="$1" ; AGE="$2" ; LOCATION="$3"
    

    【讨论】:

    • 在mysql命令中添加-N来抑制列名,这样会更好用
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2014-03-29
    • 1970-01-01
    • 2011-01-09
    • 2021-01-26
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多