簡體   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