1
6

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 5 years have passed since last update.

シェルスクリプトでMySQLからデータ取得

Posted at

シェルスクリプトからMySQLの実行結果を、Slackへの通知やPrometheusのexporter用データの生成などに利用しています。

mysqlSelect.sh
#!/bin/bash
# シェルスクリプトからMySQL実行
# コマンド例)$ sh mysqlSelect.sh 127.0.0.1 3306 mysql_user mysql_password
# 第1引数:MySQLホスト
# 第2引数:MySQLポート
# 第3引数:MySQLユーザ
# 第4引数:MySQLパスワード

# SQL
sql="select id, name from db_name.table_name;"
echo "sql=$sql"

# SQL結果出力先
nowDateTime=(`date '+%Y%m%d%H%M%S'`)
sqlResult="./logs/mysqlSelect_${nowDateTime}.log"

# SQL実行
$(mysql -h $1 -P $2 -u $3 -p"$4" -N -e "${sql}" > $sqlResult)

# SQL実行結果
cat $sqlResult
sqlCount=`cat $sqlResult | wc -l`
echo "sqlCount=$sqlCount"
1
6
0

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
1
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?