シェルスクリプトを使用してmysqlクエリから動的変数を渡す方法

シェルスクリプトを使用してmysqlクエリから動的変数を渡す方法

これは私のコードの一部です。

sample_1=''
sample_1_is_cancelled=''
sample_2=''
sample_2_is_cancelled=''
sample_3=''
sample_3_is_cancelled=''
sample_4=''
sample_4_is_cancelled=''
sample_5=''
sample_5_is_cancelled=''

while read -r insert
do
 eval sample_$i=$(echo $insert| awk -F'|' '{print $1}')
 eval sample_$i_is_cancelled=$(echo $insert| awk -F'|' '{print $2}')
         i=$(( i + 1 ))
         
         done < $logpath/source.txt

mysql -uroot -p -e" insert into ttable(sample_1, sample_1_is_cancelled, sample_2, sample_2_is_cancelled, sample_3, sample_3_is_cancelled, sample_4, sample_4_is_cancelled, sample_5, sample_5_is_cancelled)
                values($sample_1, $sample_1_is_cancelled, $sample_2 $sample_2_is_cancelled, $sample_3, $sample_3_is_cancelled, $sample_4, $sample_4_is_cancelled, $sample_5, $sample_5_is_cancelled);"

最大5つの値セットがあります。少なくとも1セット。

以下の変数をエコーできます。

eval echo \$sample_$i
eval echo \$sample_${i}_is_cancelled

ただし、同じ方法で挿入クエリの外部に渡すことはできません。どんな提案でも…助けてください。

ベストアンサー1

以下は、2つの配列(「フィールド」と「値」)を使用してこれを実行する方法の例です。

#!/bin/bash

declare -a fields values

infile="./source.txt"
#infile="$logpath/source.txt"

i=0
while read -r insert; do
  # split "$insert" into a and b, using | as delimiter
  a="${insert%|*}"
  b="${insert#*|}"

  # create the field names from the loop counter $i
  let i++
  sfield="sample_$i"
  cfield="sample_${i}_is_cancelled"

  fields+=("$sfield" "$cfield")
  values+=("$a" "$b")
done < "$infile"


# show what's in the arrays:
declare -p fields
echo
declare -p values

# now build the SQL string, in parts:

# field names don't need to be quoted
f=$(printf "%s, " "${fields[@]}" | sed -e 's/, $//')

# this assumes values are strings and need to be quoted
v=$(printf "'%s', " "${values[@]}" | sed -e 's/, $//')

sql="$(printf "insert into ttable(%s) values (%s);" "$f" "$v")"

echo
echo "mysql -uroot -p -e \"$sql\""

次のsources.txtファイルが提供されます。

$ cat source.txt 
one|two
three|four
foo|bar
junk|more junk

スクリプトを実行すると、次の出力が生成されます。

declare -a fields=([0]="sample_1" [1]="sample_1_is_cancelled" [2]="sample_2" 
  [3]="sample_2_is_cancelled" [4]="sample_3" [5]="sample_3_is_cancelled"
  [6]="sample_4" [7]="sample_4_is_cancelled")

declare -a values=([0]="one" [1]="two" [2]="three" [3]="four"
  [4]="foo" [5]="bar" [6]="junk" [7]="more junk")

mysql -uroot -p -e "insert into ttable(sample_1, sample_1_is_cancelled, sample_2,
  sample_2_is_cancelled, sample_3, sample_3_is_cancelled,
  sample_4, sample_4_is_cancelled) values ('one', 'two', 'three', 'four',
  'foo', 'bar', 'junk', 'more junk');"

(読みやすくするために、改行とインデントを追加してください)


注:シェルスクリプト自体のフィールド名または値でより多くの操作を実行する必要がある場合(たとえば、SQL挿入ステートメントでのみ使用するのではなく)、2つの連想配列(サンプル用の1つ、1つはサンプル用)を使用することをお勧めします。 。キャンセルサンプルの場合)$ sfield変数と$ cfield変数をこれらの配列のキーとして使用します。私はこのようなスクリプトの作成を始めましたが、作業が複雑すぎることに気付きました(SQL文字列を構成するためにフィールドと値をマージするためにもっと作業が必要です)、インデックス配列$ fieldsと$ valuesを使用して単純化しました。

おすすめ記事