3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ShellScript で MySQL の実行結果を変数に格納する

Last updated at Posted at 2021-09-07

概要

ShellScript で簡易的な処理を書いていた際、MySQLの結果を変数に格納したくなったことがあった。
その際にやったことをメモしておく。

前提

  • ここで記載するのはMySQLの実行結果が1行の場合の方法。2行以上の場合はさらに工夫が必要。

結論

result=`mysql --defaults-extra-file=mysql.cnf -u user -e "SELECT id, title, description FROM table WHERE id = 123" -E | sed -e "1d" | sed -e 's/: /="/g' | sed -e 's/$/"/'`
eval ${result}
# 結果出力
echo ${id}
echo ${title}
echo ${description}

解説

ワンラインでゴリゴリ書いているので分解しながら解説する。

mysqlコマンド

mysql --defaults-extra-file=mysql.cnf -u user -e "SELECT id, title, description FROM table WHERE id = 123" -E

MySQLコマンドの最後の-Eオプションをつけることで以下のように実行結果が縦出力される。

*************************** 1. row ***************************
 id: 123
 title: タイトル
 description: 説明文

sedで置換

まずは上記の実行結果から邪魔な1行目を取り除く

sed -e "1d"

続いて「: 」を「="」に置換し…

sed -e 's/: /="/g'

さらに行末に「"」を追加する。

sed -e 's/$/"/'

すると最終的に以下のような出力結果になる。

 id="123"
 title="タイトル"
 description="説明文"

evalでコマンドとして実行

上記の結果を eval で実行すると、もうお分かりの通り、カラム名と同じ変数「id」「title」「description」にそれぞれ値を代入する式となる。

eval ${result}

1カラムのみ取得したい場合

上記は複数カラムを一気に変数に格納する方法だが、1カラムのみの場合はもっとシンプルに書ける。

title=`mysql --defaults-extra-file=mysql.cnf -u user -e "SELECT title FROM table WHERE id = 123" -BN`
# 結果出力
echo ${title}

まとめ

シェルでゴリゴリ書くのは楽しいのだが、ここまでくるとそろそろ他の言語を使ったほうが書きやすいと思う。
でも途中までシェルで書いたし、ここで他の言語にいくのも癪なので、意地というか、どうしてもシェルで完成させたくなってしまう。
そんなときに使ってほしい。

3
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?