bash でよく使うやつ
桁指定で表示する
-bash ~$ i=1 -bash ~$ printf "%02d" $i 01-bash ~$
改行させるなら
-bash ~$ printf "%02d\n" $i 01
整数の加算
expr とさらばできる
-bash ~$ i=0 -bash ~$ ((i++)) -bash ~$ echo $i 1
C 言語っぽい for 文がかける
$ for (( i=0; i<3; i++)) do echo $i; done 0 1 2
正規表現でマッチングできる
in 句のように使える
-bash ~$ a=abc -bash ~$ [[ $a =~ c ]] && echo "matched" matched -bash ~$ [[ $a =~ d ]] && echo "matched" -bash ~$
リスト
# リストの作成 -bash ~$ i=("a" "b" "c") # リストの展開 -bash ~$ echo ${i[0]} a -bash ~$ echo ${i[1]} b -bash ~$ echo ${i[2]} c -bash ~$ echo ${i[@]} a b c -bash ~$ echo ${i[*]} a b c # 要素の数 -bash ~$ echo ${#i[@]} 3 # 要素の追加 -bash ~$ i+=("d") -bash ~$ echo ${i[@]} a b c d -bash ~$ echo ${#i[@]} 4
引数を順番に処理する
$ cat shift_test.sh #!/bin/bash echo $1 echo $# shift echo $1 echo $# $ sh shift_test.sh 1 2 1 2 2 1
引数がなくなるまでループする
$ cat shift_test.sh #!/bin/bash for (( i=0; $#>0; )) do echo $1 shift done echo "exit" && exit 0 $ sh shift_test.sh 1 2 3 4 5 1 2 3 4 5 exit
i=0
がないと shift_test.sh: line 3: syntax error: arithmetic expression required
と怒られる
ユーザからの入力があるまでスクリプト実行を待機する
$ cat shift_test.sh #!/bin/bash for (( i=0; $#>0; )) do echo $1 shift if [ $# = 1 ]; then read -p "this is last loop. hit enter key to continue." fi done echo "exit" && exit 0 $ sh shift_test.sh 1 2 3 4 5 1 2 3 4 this is last loop. hit enter key to continue. 5 exit
中断するときは ctrl + c
関数名を表示する
$ cat func_test.sh #!/bin/bash function mytest() { echo ${FUNCNAME} } mytest $ sh func_test.sh mytest
printf で文字列を置換する
$ a=test $ printf '%s\n' $a test
ファイルの行番号を表示する
以下の様な txt を用意して、
$ cat raw.txt nikko nikko ni- anata no heart ni niko niko ni- egao todokeru yazawa niko niko- nikoni- tte yonde love niko
while ループでまわす
$ cat raw.txt | while read line; do printf '%2d %s\n' ${lineno} "${line}"; (( lineno++ )) ; done 1 nikko nikko ni- 2 anata no heart ni 3 niko niko ni- 4 egao todokeru 5 yazawa niko niko- 6 nikoni- tte yonde 7 love niko
実行中のファイルの行番号を表示する
$ cat raw.sh #!/bin/bash echo ${LINENO} echo ${LINENO} echo ${LINENO} echo ${LINENO} function mytest() { echo ${FUNCNAME} ${LINENO} } echo ${LINENO} echo ${LINENO} mytest echo ${LINENO} echo ${LINENO} $ sh raw.sh 3 4 5 6 13 14 mytest 10 18 19
PostgreSQL を暖気する
postgresql は linux においてファイルキャッシュを信用するので、
データファイルを cat
してあげると自然とデータがメモリに乗ります。
メモリ大容量時代が到来していますので、このようなニーズもあるのかなと。
postgresql の再起動後などに以下のようなコマンドを実行することで、全てのデータファイルをメモリに乗せることができます。
find "${PG_DATA}" -name "*" -exec cat {} \;
また、特定のテーブルを除いて暖気したい要求がありましたのでスクリプトを書いてみました。
#!/bin/bash # warming_up_database.sh set -e PG_HOST="host" PG_USER="user" PG_PORT="5432" PG_DATABASE="user_table" PG_DATA="db_cluster_dir" PG_CONN="-U ${PG_USER} -H ${PG_HOST} -p ${PG_PORT} -d ${PG_DATABASE}" warming_up_database_with_exclude_file() { # generate exclude string for (( i=1; $#>0; )) do target=$1 # need to do without password, using .pgpass or pg_hba.conf data_file_name=$(/usr/pgsql-9.3/bin/oid2name ${PG_CONN} -t ${target} -q | awk {'print $1'}) if [ -z "${data_file_name}" ]; then read -p "no datafile -> $1 . if you want continue, hit Enter key." break fi if [ $i = 1 ]; then exclude=("-name ${data_file_name}") else exclude+=(" -o -name ${data_file_name}") fi shift done # warming up ! [ -n "${exclude[*]}" ] && time find ${PG_DATA} ${exclude[@]} -prune -o -print -exec cat {} \; > /dev/null 2>&1 \ || echo "${FUNCNAME} failed." && exit 1 } warming_up_database_all() { time find "${PG_DATA}" -name "*" -exec cat {} \; > /dev/null 2>&1 \ || echo "${FUNCNAME} failed." && exit 1 } print_usage() { echo "Usage:" echo "do all warming up => $0 --all" echo "do warming up with exclude file => $0 --exclude exclude_table_name" exit 1 } case $1 in --help|*) print_usage ;; --exclude) if [ $# -lt 2 ]; then print_usage exit 1 fi shift warming_up_database_with_exclude_file $@ exit 0 ;; --all) warming_up_database_all exit 0 ;; esac
CentOS7 に pip と awscli をインストール
vagrant 上の CentOS7 です。
# cat /etc/centos-release CentOS Linux release 7.1.1503 (Core)
普通に yum だとインストールできませんでした。 結論を先に記載すると 4 コマンド実行で pip と awscli のインストールができました。
# yum install epel-release # yum install python-pip # pip install pip --upgrade $ pip install awscli --user
以下は経緯というかログです。
# yum clean all Loaded plugins: fastestmirror Cleaning repos: base extras updates Cleaning up everything Cleaning up list of fastest mirrors # # yum install python-pip Loaded plugins: fastestmirror - 略 - No package python-pip available. Error: Nothing to do
デフォルトのレポジトリからは yum できなかったので epel からインストールしてみます。
まずは epel レポジトリを追加します。
# yum install epel-release Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: ftp.tsukuba.wide.ad.jp * extras: ftp.tsukuba.wide.ad.jp * updates: ftp.tsukuba.wide.ad.jp Resolving Dependencies --> Running transaction check ---> Package epel-release.noarch 0:7-5 will be installed --> Finished Dependency Resolution Dependencies Resolved =========================================================================================================================================================================================================================================================================================================================== Package Arch Version Repository Size =========================================================================================================================================================================================================================================================================================================================== Installing: epel-release noarch 7-5 extras 14 k Transaction Summary =========================================================================================================================================================================================================================================================================================================================== Install 1 Package Total download size: 14 k Installed size: 24 k Is this ok [y/d/N]: y Downloading packages: epel-release-7-5.noarch.rpm | 14 kB 00:00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : epel-release-7-5.noarch 1/1 Verifying : epel-release-7-5.noarch 1/1 Installed: epel-release.noarch 0:7-5 Complete!
続いて pip をインストールします。
# yum install python-pip --enablerepo=epel Loaded plugins: fastestmirror epel/x86_64/metalink | 5.2 kB 00:00:00 epel | 4.3 kB 00:00:00 (1/3): epel/x86_64/updateinfo | 374 kB 00:00:00 (2/3): epel/x86_64/group_gz | 169 kB 00:00:00 (3/3): epel/x86_64/primary_db | 3.6 MB 00:00:00 Loading mirror speeds from cached hostfile * base: ftp.tsukuba.wide.ad.jp * epel: ftp.riken.jp * extras: ftp.tsukuba.wide.ad.jp * updates: ftp.tsukuba.wide.ad.jp Resolving Dependencies --> Running transaction check ---> Package python-pip.noarch 0:7.1.0-1.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved =========================================================================================================================================================================================================================================================================================================================== Package Arch Version Repository Size =========================================================================================================================================================================================================================================================================================================================== Installing: python-pip noarch 7.1.0-1.el7 epel 1.5 M Transaction Summary =========================================================================================================================================================================================================================================================================================================================== Install 1 Package Total download size: 1.5 M Installed size: 6.6 M Is this ok [y/d/N]: y Downloading packages: warning: /var/cache/yum/x86_64/7/epel/packages/python-pip-7.1.0-1.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY 12% [================- ] 0.0 B/s | 196 kB --:--:-- ETA Public key for python-pip-7.1.0-1.el7.noarch.rpm is not installed python-pip-7.1.0-1.el7.noarch.rpm | 1.5 MB 00:00:01 Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 Importing GPG key 0x352C64E5: Userid : "Fedora EPEL (7) <epel@fedoraproject.org>" Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5 Package : epel-release-7-5.noarch (@extras) From : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 Is this ok [y/N]: y Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : python-pip-7.1.0-1.el7.noarch 1/1 Verifying : python-pip-7.1.0-1.el7.noarch 1/1 Installed: python-pip.noarch 0:7.1.0-1.el7 Complete!
できた、けど古いようです。執筆時点での pip のバージョンは 7.1.2 です。
upgrade してみます。
# pip install pip --upgrade /usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning You are using pip version 7.1.0, however version 7.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. /usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Collecting pip Downloading pip-7.1.2-py2.py3-none-any.whl (1.1MB) 100% |████████████████████████████████| 1.1MB 452kB/s Installing collected packages: pip Found existing installation: pip 7.1.0 Uninstalling pip-7.1.0: Successfully uninstalled pip-7.1.0 Successfully installed pip-7.1.2
upgrade できました。
# pip --version pip 7.1.2 from /usr/lib/python2.7/site-packages (python 2.7)
ついでに awscli をインストールします。
ここでは一般ユーザー向けにインストールしてみます。
$ pip install awscli --user Collecting awscli /usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Downloading awscli-1.9.1-py2.py3-none-any.whl (797kB) 100% |████████████████████████████████| 798kB 549kB/s Collecting rsa<=3.3.0,>=3.1.2 (from awscli) Downloading rsa-3.2-py2.py3-none-any.whl (43kB) 100% |████████████████████████████████| 45kB 7.0MB/s Collecting colorama<=0.3.3,>=0.2.5 (from awscli) Downloading colorama-0.3.3.tar.gz Collecting botocore==1.3.1 (from awscli) Downloading botocore-1.3.1-py2.py3-none-any.whl (2.1MB) 100% |████████████████████████████████| 2.1MB 207kB/s Collecting docutils>=0.10 (from awscli) Downloading docutils-0.12.tar.gz (1.6MB) 100% |████████████████████████████████| 1.6MB 289kB/s Collecting pyasn1>=0.1.3 (from rsa<=3.3.0,>=3.1.2->awscli) Downloading pyasn1-0.1.9-py2.py3-none-any.whl Collecting jmespath<1.0.0,>=0.7.1 (from botocore==1.3.1->awscli) Downloading jmespath-0.9.0-py2.py3-none-any.whl Collecting python-dateutil<3.0.0,>=2.1 (from botocore==1.3.1->awscli) Downloading python_dateutil-2.4.2-py2.py3-none-any.whl (188kB) 100% |████████████████████████████████| 192kB 2.0MB/s Collecting six>=1.5 (from python-dateutil<3.0.0,>=2.1->botocore==1.3.1->awscli) Downloading six-1.10.0-py2.py3-none-any.whl Installing collected packages: pyasn1, rsa, colorama, jmespath, six, python-dateutil, docutils, botocore, awscli Running setup.py install for colorama Running setup.py install for docutils Successfully installed awscli botocore colorama docutils jmespath pyasn1 python-dateutil rsa six /usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning
できました。
$ aws --version aws-cli/1.9.1 Python/2.7.5 Linux/3.10.0-229.14.1.el7.x86_64 botocore/1.3.1
powershell で X-ASPNET-VERSION ヘッダを削除する
サーバ全体で無効化する方法がないか調べてみたところ msdn ブログがヒットしました。
方法は 2 種類あって、web.config に追加する方法と、サーバレベルでサーバ変数を利用した rewrite を行う方法があるようです。
ただし、後者は ヘッダそのものではなく、ヘッダの値を隠蔽
するというものになっています。
web.config での方法
以下の 3 行をトップレベルの web.config に追記します。
<system.web> <httpRuntime enableVersionHeader="false" /> </system.web>
または下記コマンドを実行します。
c:\windows\system32\inetsrv\appcmd.exe set config -section:system.web/httpRuntime -enableVersionHeader:false /commit:webroot /clr:4
.NET2 の場合は /clr:2
とします。
すると ROOT である C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\Web.config
に上記内容が追加されます。
IISフォーラム先生ありがとうございます。
System.Web in Applicationhost.config not working anymore (IIS8.5) : The Official Microsoft IIS Forums
applicationHost.config での方法
IIS 8 からは applicationHost.config での system.web セクションは廃止されたとのこと。
rewrite での方法
Please note that it will not remove the header all together but it will remove the value of it.
あまり意味はなさそうですが、とりあえずやってみようということで、サイト内の手順に沿って IIS マネージャから設定したところ、 applicationHost.config
に設定が追加されてしまいました。
<system.webServer> <rewrite> <allowedServerVariables> <add name="RESPONSE_X-ASPNET-VERSION" /> </allowedServerVariables> <outboundRules> <rule name="RESPONSE_X-ASPNET-VERSION"> <match serverVariable="RESPONSE_X-ASPNET-VERSION" pattern=".+" /> <action type="Rewrite" /> </rule> </outboundRules> </rewrite> </system.webServer>
powershell でできないか調べてみたところ、いくつかのコマンドレットを使うとよさそうです。
Get-WebConfigurationProperty
Add-WebConfigurationProperty
Set-WebConfiguration
スクリプトは以下のようになりました。
if 文があるのは無駄に chef で実行されることを想定したのでちょっとだけ冪等性を考えたためです。
# add allowedServerVariables $asv = Get-WebConfigurationProperty ` -filter "//rewrite/allowedServerVariables/add"` -name name if ($asv -eq $null) { Add-WebConfigurationProperty ` -Filter "//rewrite/allowedServerVariables" ` -PSPath "IIS:\" ` -Name "Collection" ` -Value @{name="RESPONSE_X-ASPNET-VERSION"} } # add rule $rule = Get-WebConfigurationProperty ` -filter "//rewrite/outboundRules/rule[@name='REMOVE_X-ASPNET-VERSION']/match"` -name serverVariable if ($rule -eq $null) { Add-WebConfigurationProperty ` -Filter "//rewrite/outboundRules" ` -PSPath "IIS:\" ` -Name "Collection" ` -Value @{name="REMOVE_X-ASPNET-VERSION"} Set-WebConfiguration ` -Filter "//rewrite/outboundRules/rule[@name='REMOVE_X-ASPNET-VERSION']/match" ` -PSPath "IIS:\" ` -Value @{serverVariable="RESPONSE_X-ASPNET-VERSION";pattern=".+"} Set-WebConfiguration ` -Filter "//rewrite/outboundRules/rule[@name='REMOVE_X-ASPNET-VERSION']/action" ` -PSPath "IIS:\" ` -Value @{type="Rewrite"} }
ていうか、カスタムエラーページのハンドリングをちゃんとしないと。。。
ubuntu に vagrant 環境をつくる
余った PC に ubuntu-mate をインストールしたのでついでに vagrant 環境を作ってみました。
環境
PC | OS |
---|---|
thinkpad X1 | ubuntu 15.04 |
VT-X の有効化
BIOS から VT-X を有効化します。 thinkpad X1 の BIOS 起動手順はこちら
Security
-> Virtualization
-> Intel VT
に進み、Intel Virtualization
Technology
を Enabled
にして再起動します。
Virtual Box のインストール
普通に公式から deb パッケージをインストールしただけだと不足パッケージがあるようで、仮想マシンがうまく動作しませんでした。
冒頭で紹介させていただいたサイトに記載のリポジトリを追加して apt-get
します。
sudo echo "deb http://download.virtualbox.org/virtualbox/debian raring contrib" > /etc/apt/sources.list sudo wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add - sudo apt-get update sudo apt-get install virtualbox
vagrant のインストール
公式サイト から deb パッケージをダウンロードしてインストールします。
mkdir ~/src cd ~/src wget https://dl.bintray.com/mitchellh/vagrant/vagrant_1.7.2_i686.deb sudo dpkg --install vagrant_1.7.2_i686.deb
仮想環境を起動する
作業用ディレクトリを作成して、その中で作業します。 今回は公式の centos/7 を利用します。
mkdir -p ~/vagrant/centos7 cd ~/vagrant/centos7 vagrant init centos/7
init 完了後、作成された VagrantFile を1行だけ編集します。
# 29行目をコメントアウト config.vm.network "private_network", ip: "192.168.33.10"
新しめの vagrant コマンドでは公式の box ならば(?) vagrant up
のみでダウンロードから始まるので vagrant box add
しなくていいみたいです。
vagrant up --provier virtualbox
--provider virtualbox
はなくてもOKでした。
その後、vagrant 起動中に自動で yum update
が実行され、host / guest 間でのファイル共有のための rsync フォルダが作成され、そのまま centos が起動しました。
box にも追加されています。
$ vagrant box list centos/7 (virtualbox, 1509.01)
ssh ログインしてバージョンを確認してみます。
$ vagrant ssh [vagrant@localhost ~]$ cat /etc/centos-release CentOS Linux release 7.1.1503 (Core)
ログインできました^^
こちらを参考にさせていただきました。 Ubuntu 15.04にVirtualbox、Vagrantをインストール
postgresql で trigger とその trigger が動作するテーブルの一覧を取得する
SELECT event_object_schema, event_object_table, trigger_schema, trigger_name FROM information_schema.triggers
結果
event_object_schema | event_object_table | trigger_schema | trigger_name ---------------------+-----------------------------+----------------+------------------------------------------- schema | user_table | schema | user_trigger
*
だと action_timing
や event_manipulation
も取得できます。information_schema 便利です。
\d information_schema.triggers View "information_schema.triggers" Column | Type | Modifiers ----------------------------+------------------------------------+----------- trigger_catalog | information_schema.sql_identifier | trigger_schema | information_schema.sql_identifier | trigger_name | information_schema.sql_identifier | event_manipulation | information_schema.character_data | event_object_catalog | information_schema.sql_identifier | event_object_schema | information_schema.sql_identifier | event_object_table | information_schema.sql_identifier | action_order | information_schema.cardinal_number | action_condition | information_schema.character_data | action_statement | information_schema.character_data | action_orientation | information_schema.character_data | action_timing | information_schema.character_data | action_reference_old_table | information_schema.sql_identifier | action_reference_new_table | information_schema.sql_identifier | action_reference_old_row | information_schema.sql_identifier | action_reference_new_row | information_schema.sql_identifier | created | information_schema.time_stamp |
vpc endpoint から s3 へのアクセス制御 (bucket policy)
記載された vpce
と IPアドレスのみ許可する設定例です。
{ "Version": "2012-10-17", "Id": "vpce-restrict", "Statement": [{ "Sid": "Allow-VPCE", "Action": "s3:*", "Principal": { "AWS": "*" }, "Effect": "Allow", "Resource": [ "arn:aws:s3:::bucket-name*", "arn:aws:s3:::bucket-name/*", ], "Condition": { "StringEquals": { "aws:sourceVpce": [ "vpce-********" ] } } }, { "Sid": "IPAddress-restrict", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:*", "Resource": [ "arn:aws:s3:::bucket-name*", "arn:aws:s3:::bucket-name/*", ], "Condition": { "IpAddress": { "aws:SourceIp": [ "***.***.***.***/**" ] } } }] }
この場合、StringEquals
だと許可、 StringNotEquals
だと拒否になりますので、うまいぐあいに使い分けができます。
というか、これに気づかなくてハマってしまった・・・