【问题标题】:BASH MySQL output to dynamic variablesBASH MySQL 输出到动态变量
【发布时间】:2020-07-14 13:15:28
【问题描述】:

我正在使用以下 BASH mysql 语句从我的数据库中获取数据。

mysql -N -u root --password=ROOT DB -h 127.0.0.1 -e "SELECT * FROM site where id like '1234'" | while read A B C D E F G H I J K L M N O P Q R S T U V W X Y Z; do
    echo $A
    echo $B
done

要获得 A 到 Z 的所有值,这似乎是一个冗长的方法。

我怎样才能更好地做到这一点,并根据read 值名称和结果创建变量。 ?

例如: create var A which contains value of $A and do this all the way upto var Z containing the value of $Z

这只是一个示例,这些值不会被称为 A-Z,而是具有专有名称。有没有办法根据真正的专有名称创建变量,然后将值关联到它?

例如:

mysql -N -u root --password=ROOT DB -h 127.0.0.1 -e "SELECT * FROM site where id like '1234'" | while read site_id site_location site_size etc.......;做

谢谢

【问题讨论】:

    标签: mysql bash variables


    【解决方案1】:

    mysql 调用需要以这种方式传入 while 循环:

    while read -r site_id site_location site_size _ ; do
      echo "$site_id" "$site_location" "$site_size"
    done < <(
      mysql -N -u root --password=ROOT DB -h 127.0.0.1 -e "SELECT * FROM site where id like '1234'"
    )
    

    &lt; &lt;(command) 重定向允许command 在子shell 中执行,但提供主线程的read。所以当它read -r var1 var2 ... varn &lt; &lt;(command)时,变量对主线程有效。

    command | read -r varcommand 在主线程中执行,read 在子shell 中执行,而var 仅在子shell 中有效。

    从表中获取与每个列名匹配的变量名

    此脚本读取表描述并创建一个包含列名的vars 数组。

    它使用间接读取、创建和打印这些名称的每个 shell 变量。

    #!/usr/bin/env bash
    
    # Pupulate the vars array with the column names from the table
    IFS=$'\n' read -r -d '' -a vars < <(
      mysql -N -u root --password=ROOT DB -h 127.0.0.1 -e 'SHOW COLUMNS FROM site' |
        cut -d ' ' -f1
    )
    
    # Output column headers
    printf '%s\t' "${vars[@]}"
    
    # read and create variables names matching column names
    while read -r "${vars[@]}"; do
      for varname in "${vars[@]}"; do
        # Use ! indirection to print the value for the variable
        printf '%s\t' "${!varname}"
      done
    done < <(
      mysql -N -u root --password=ROOT DB -h 127.0.0.1 -e "SELECT * FROM site where id like '1234'"
    )
    

    【讨论】:

    • 感谢这有帮助:)
    猜你喜欢
    • 2018-02-20
    • 2012-04-28
    • 1970-01-01
    • 2015-02-24
    • 2014-06-02
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多