[linux: bash] Bash - Shell script on linux. #linux
プロビジョニングとか定型処理とか、シェルで行う一連の作業コマンドを「自動化」し、まとめておける。いわゆるバッチ。おそらく一番使う機会が多いのは Linux 系 OS の Bash シェルで叩くケース。ファイルの実行権限あたりで怒られることが多いのでファイルのパーミッションとオーナーに注意。
通常 Bash は exit 0
で終了した際に「正常終了」と解釈され、0 以上のステータスコードを吐きながら終了 ( exit 1
など ) した際に異常終了と解釈される。複数のバッチが連動して動作するパイプラインなどでは、異常終了を吐いた時点で継続する処理が落ちるのが慣例。
if []
は if test
コマンドのエイリアス
[ "A" = "A" ]
のようにスペースを入れて「引数」として渡さないとエラー&&
や OR ||
は利用可能!=
は利用できない
!
で代替if [ ! $FOO ]; then
<, <=, >, >=
は利用できない
-lt, -le, -gt, -ge
でそれぞれ代替if [ $FOO -lt $BAR ]; then
-d ${DIR_PATH}
でディレクトリ存在確認-f ${FILE_PATH}
でファイル存在確認$?
でとれる
#!/bin/bash
LOCK_FILE="/usr/local/app/foo.lock"
APP_DIR="/usr/local/app"
if [ -f ${LOCK_FILE} ] && [ -d ${APP_DIR} ]; then
echo "ファイルとディレクトリが存在します"
else
echo "ファイルかディレクトリのいずれかが存在しません"
fi
$ sudo su -c "echo hogehoge >> temp.txt"
# ファイルだけでなくディレクトリも対象なので注意
# ren 置換する文字列 置換後の文字列 ファイル名 ファイル名2 ...
# -n オプションを第一引数に追加で結果をテスト可能
$ ren 2014 2015 2014-*.txt
$ : > ${FILENAME}
# refs: http://baqamore.hatenablog.com/entry/2017/06/16/204217
expect -c "
spawn bash -c \"echo ${path_is} | sudo tee -a /etc/shells\"
expect \"Password:\"
send \"${PASSWORD}\n\"
interact
"
$ sed -i '$a\timezone = '\''Asia/Tokyo'\''' /var/lib/pgsql/data/postgresql.conf
# エスケープしたものをエスケープする的な
# 末尾追加パターン
$ sed -i '$a\EnableMMAP off' /etc/httpd/conf/httpd.conf
$ sed -i '$a\EnableSendfile off' /etc/httpd/conf/httpd.conf
# 置換パターン
$ sed -i -e "s/AllowOverride None/AllowOverride All/g" /etc/httpd/conf/httpd.conf
# http://qiita.com/kurosawa_kuro/items/61676cb91e0e45b87705
$ ln -s ${LINK_DIST} ${LINK_NAME}
$ mysql -u${DB_USER} -p${DB_PASS} -f ${DB_NAME} < /var/www/.migration/init.sql
$ mysqldump -u ${DB_USER} -p${DB_PASS} ${DB_NAME} > /var/www/.migration/dump.sql
#!/bin/bash
mysql -u ${DB_ROOT} --password=${DB_ROOT_PW} <<EOF
create user '${DB_USER}'@'localhost' identified by '${DB_PASS}';
create database ${DB_NAME} default character set utf8mb4;
grant all on ${DB_NAME}.* to '${DB_USER}'@'localhost' identified by '${DB_PASS}';
EOF
#!/bin/bash
sudo yum -y install expect
expect -c "
set timeout -1
spawn mysql_secure_installation
expect \"Enter current password for root (enter for none):\"
send \"\n\"
expect \"Set root password?\"
send \"y\n\"
expect \"New password:\"
send \"${DB_PASS}\n\"
expect \"Re-enter new password:\"
send \"${DB_PASS}\n\"
expect \"Remove anonymous users?\"
send \"y\n\"
expect \"Disallow root login remotely?\"
send \"y\n\"
expect \"Remove test database and access to it?\"
send \"y\n\"
expect \"Reload privilege tables now?\"
send \"y\n\"
expect eof exit 0
"