LoginSignup
8
8

More than 5 years have passed since last update.

コマンドの結果を空白で区切って配列に格納。

Last updated at Posted at 2015-05-01
[root@testsv ~]# curl -Lk http://google.com -o /dev/null -w '%{http_code}\t%{time_total}\n' -s
200     0.133
[root@testsv ~]# 

例えば、↑な感じでcurlでHTTPの応答コードと、応答時間を拾って監視したい場合、普段だったら

[root@testsv ~]# HOGE=`curl -Lk http://google.com -o /dev/null -w '%{http_code}\t%{time_total}\n' -s`
[root@testsv ~]# echo $HOGE
200 0.157
[root@testsv ~]# echo $HOGE |awk '{print $1}'
200
[root@testsv ~]# echo $HOGE |awk '{print $2}'
0.157
[root@testsv ~]# RES_CODE=`echo $HOGE |awk '{print $1}'`
[root@testsv ~]# RES_TIME=`echo $HOGE |awk '{print $2}'`
[root@testsv ~]# echo $RES_CODE
200
[root@testsv ~]# echo $RES_TIME
0.157
[root@testsv ~]#

こんな風に分けて変数に代入してたけど、配列使うともっと簡単に同じことが実現できた。

[root@testsv ~]# arr=(`curl -Lk http://google.com -o /dev/null -w '%{http_code}\t%{time_total}\n' -s |awk '{print}'`)
[root@testsv ~]# echo ${arr[*]}
200 0.124
[root@testsv ~]# 
[root@testsv ~]# echo ${arr[0]}
200
[root@testsv ~]# echo ${arr[1]}
0.124
[root@testsv ~]# 

こんな感じで配列に格納する。

これで、シェルスクリプト内でいい感じにできそう。

[root@testsv ~]# cat  test.sh
#!/bin/sh
arr=(`curl -Lk http://google.com -o /dev/null -w '%{http_code}\t%{time_total}\n' -s |awk '{print}'`)
echo "google.comからの応答番号は${arr[0]}でした。"
echo "応答時間はecho ${arr[1]}(sec)でした。"
[root@testsv ~]# 
[root@testsv ~]# sh  test.sh
google.comからの応答番号は200でした。
応答時間はecho 0.230(sec)でした。
[root@testsv ~]# 

しょぼいけど、こんな感じ?
awkの-Fでセパレータ指定してやれば、わりと何でもいけそう。

ワンラインでやりたいって言ってくれた先輩に感謝。

8
8
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
8
8