繁体   English   中英

BASH MySQL 输出到动态变量

[英]BASH MySQL output to dynamic variables

我正在使用以下 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

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

例如:

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 -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调用需要通过这种方式传入 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'"
)

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

command | read -r var 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'"
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM