それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

指定したコマンドだけsudoでパスワードを除外する。逆にパスワードを必須にする

頻繁に使うコマンドで パスワード入力してるとオオカミ少年になる。

たとえば、yum/aptコマンドは使わない日なんて無いに等しいと思うの。

sudo yum install 

このようなコマンドでパスワードを入力してると、大げさではないかと思った。

また入力を頻繁に行うと、ショルダーHackの危険性も高まる。

指定したコマンドはパスワードなしでsudo できるようにする。

takuya さんは、wheel にはいってるので sudo 出来ます。

uid=1000(takuya) gid=1000(takuya) groups=1000(takuya),10(wheel)

takuya さんは yum 実行時だけ パスワードを不要にしました。

takuya ALL=NOPASSWD : /usr/bin/yum

逆にパスワードを必須にする。

takuya ALL=PASSWD : /usr/sbin/halt, /usr/sbin/reboot, /usr/sbin/shutdown

デフォルトでは、sudo のパスワードの入力の効果はしばらく継続するので、その間にうっかりreboot しないように自分で自分に首輪をつける。

同じように グループやコマンドセットも使える。

sudoers なので、グループやコマンドのエイリアス登録も使える。

Cmd_Alias REBOOT =  /usr/sbin/halt, /usr/sbin/reboot, /usr/sbin/shutdown
%wheel  ALL=PASSWD :  REBOOT

参考資料

man sudoers

端末(デバイス)の向きを判定する

画面の向きを判定するには CSS の matchMedia を使う

画面の向きが横か縦か判別することが出来る

css で縦の時だけに適用されるスタイルはこれ。

@media (orientation : portrailt ){

}

このCSSのマッチングを、Javascript 側から行うには

window.matchMedia("( orientation: portrailt )")

こうなる。

これをまとめるとこうなる。

window.isLandscape = function(){ return window.getOrientation() == "landscape"}
window.isPortrait  = function(){ return window.getOrientation() == "portrait"}
window.getOrientation = function(){
  return ["portrait", "landscape"].find( 
      function(s){ 
            return window.matchMedia(`( orientation: ${s} )`).matches}
  )
}

参考資料

https://developer.mozilla.org/en/docs/Web/API/Window/matchMedia

WEB経由でファイルのパーミッション・オーナーを変更する

ブラウザ経由でファイルのownerを弄りたいな

でも、 chown って root しか許可されてないんですよね。

chown するとパーミッション管理が破綻するおそれがあるからでしょうね。

解決策 : sudoers に記述する

もう、sudoers 使うしか無いですね。

Cmnd_Alias CH= /bin/chown, /bin/chmod, /bin/chgrp
www-data  ALL=NOPASSWD: CH

sudoers 仕込んだ上で、 php+apache で試してみる。

<?php

$ret_var ;
$outout;

exec ( "sudo chown takuya /var/www/test " );

コレで出来る。

ただ、どこでもパーミッションを変えられても、甘いので、ちょっとだけ制限を加えておく

<?php

function sudo_chown($ug, $path){
   if ( strpos ( $path, "/var/www" ) === 0 ){
       putenv("UG=$ug");
       putenv("TARGET=$path");
       shell_exec( 'sudo chown $UG $TARGET ');
       putenv("UG=");
       putenv("TARGET=");
   }
}

こんな感じかな。

感想

chown を directory の write 権限とともに管理してくれたら、ユーザー毎にchown出来そうなんだけど何で出来ないんだろう。

JSON.stringify で関数(funciton) も文字列化、JSON.parseでdeserialize する。

JavaScriptJSONはprimitiveな変数だけしか扱えなかった。

JSONというのは、本当にお前さんらはね。サムライになれないんだよ。

JSON

var obj = {"a": "takuya", "say":function(){ console.log(`My name is ${this.a}.`) } }
obj.say()
//=>My name is takuya.

このオブジェクトをJSONでString化すると

stringify すると関数消える。

JSONがサムライになれない理由がコレ。

JSON.stringify(obj)
"{"a":"takuya"}" // function 消される。

これは仕方ないんだよ。 function が定義されるタイミングで、変数のスコープもあるし。でも初回ロードとか別にスコープを気にしない時になんとかならないか調べた。

JSON で関数も保存したい!

なんとかならないか調べた。

JSON.stringify/parseの第二引数を使う。

JSON.stringify には第二引数を指定できて、オブジェクトの値をどのようにして、文字列化するか指定できる。

JSON.stringify(value[, replacer[, space]])

ここでReplacerを使えばなんとかなりそう。

文字列化関数を指定してみる。
function replacer (k,v){ 
 e if(typeof v === "function"){ return v.toString() }; 
  return v ;
}
str= JSON.stringify(obj, replacer)
//=> "{"a":"takuya","say":"function (){ console.log(`My name is ${this.a}.`) }"}"

おお?文字列化出来る。 可能性が出てきた。

JSON.parse指定してみると
JSON.parse(str)
//=>Object {a: "takuya", say: "function (){ console.log(`My name is ${this.a}.`) }"}

文字列化したから、関数も文字列になってしまう。そりゃそうだ。

JSON.parse を調べてみると

JSON.parse(text[, reviver])

replacer の逆のreciever があることが分かった。試してみよう。

JSON.parse の第二引数を使ってみる

第二引数で、文字列化した関数 を元に戻せないか試してみよう。

a = '{"a":"takuya","say":"function(){ console.log(this.a)}"}'
function reciever (k,v ) {  
  
  if ( typeof v === "string" && v.match(/^function/) ){
    return Function.call(this, "return "+ v  )();
  }
  return v 
}

var a = JSON.parse( a ,reciever)


a.say() //=>takuya

おお!?戻った戻ったよ! メソッドを入れたObjectをシリアライズして元に戻せるじゃん。

出来るじゃん!

これ、メッチャ便利じゃね?

ネストしたJSON.stringify() も大丈夫!

ネストしたらどうなるのか、試してみた。

a = '{"name":"takuya","pets": [{ "name": "taro", "say": "function(){ console.log(this.name)}" }] } '
function reciever (k,v ) {  
  
  if ( typeof v === "string" && v.match(/^function/) ){
    return Function.call(this, "return "+ v  )();
  }
  return v 
}

var a = JSON.parse( a ,reciever)


a.pets[0].say(); //=> taro

出来るじゃん。

まとめ

  • JSON.parseで関数も渡せる
  • JSON .stringify で関数が渡せる
  • JSON.stringify ( obj ,replacer) でfunction もString化出来る
  • メソッドを持ったObjectをJSONシリアライズ出来る
  • JSONで作ったオブジェクトにメソッドをもたせたまま、転送できる
  • JSONはデータ交換だけじゃなく、使い方では「インスタンス」を渡せそう。
  • JSONで関数もデシリアライズできるから、状態保存と状態の復元が手軽にできる。

ただし、parse 時の変数のスコープに差異があり、変数のスコープまで意識して完全に同じになる保証はできない。ただthis くらいはなんとかなるとわかった。工夫次第で同じスコープは再現できそう。

JSONの痒い所に手が届かない感じで、世界一のサムライになれない感じがあった。 世界が広がる。Javascriptは戦うサムライになれる。

参考資料

JSON.stringify() - JavaScript | MDN

eval() - JavaScript | MDN

Function.prototype.call() - JavaScript | MDN

JS 形式の設定ファイルを読み込むときは eval の代わりに new Function を使う - たそがれ日記

関連資料

Chrome Extension のcontent scriptでの変数隔離に対応する。 - それマグで!

UTF-8じゃないカラム作っちゃった!UTF-8にしたい

mysql でウッカリutf-8 じゃないカラムを作っちゃった。

変更することは出来ないのか?

調べたら出来そうだと分かった

Alter Table を使う

ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

これで日本語の文字化けから解消される。というかコレないと日本語で検索ができない。。。

参考資料

http://stackoverflow.com/questions/6115612/how-to-convert-an-entire-mysql-database-characterset-and-collation-to-utf-8

HDD が 壊れるとどうなるのか。Smarttoolsで見てみた結果

HDDが壊れるとどうなるのか

復旧する前に確認しておくことにした。

smart でエラーが見られるのですが、いままで手元のHDDがエラーを出したことがなかった。

エラーが出たので記念に残すことにした。

Smartでエラーが出たらこうなります。ってのを覚えておくと、復旧や調査に役に立つとおもうので残しておくことにする。

takuya@:~$ sudo smartctl -a /dev/sdb
smartctl 5.41 2011-06-09 r3365 [x86_64-linux-3.2.0-4-amd64] (local build)
Copyright (C) 2002-11 by Bruce Allen, http://smartmontools.sourceforge.net

=== START OF INFORMATION SECTION ===
Model Family:     Western Digital Caviar Green (Adv. Format)
Device Model:     WDC WD20EARS-00MVWB0
Serial Number:    WD-WMAZA0636931
LU WWN Device Id: 5 0014ee 6ab131a6e
Firmware Version: 51.0AB51
User Capacity:    2,000,398,934,016 bytes [2.00 TB]
Sector Size:      512 bytes logical/physical
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   8
ATA Standard is:  Exact ATA specification draft version not indicated
Local Time is:    Sat Jun  4 21:25:12 2016 JST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x82) Offline data collection activity
                    was completed without error.
                    Auto Offline Data Collection: Enabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        (39300) seconds.
Offline data collection
capabilities:            (0x7b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   2) minutes.
Extended self-test routine
recommended polling time:    ( 255) minutes.
Conveyance self-test routine
recommended polling time:    (   5) minutes.
SCT capabilities:          (0x3035) SCT Status supported.
                    SCT Feature Control supported.
                    SCT Data Table supported.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x002f   146   146   051    Pre-fail  Always       -       116358
  3 Spin_Up_Time            0x0027   174   159   021    Pre-fail  Always       -       6291
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       383
  5 Reallocated_Sector_Ct   0x0033   166   166   140    Pre-fail  Always       -       736
  7 Seek_Error_Rate         0x002e   200   200   000    Old_age   Always       -       0
  9 Power_On_Hours          0x0032   036   036   000    Old_age   Always       -       47139
 10 Spin_Retry_Count        0x0032   100   100   000    Old_age   Always       -       0
 11 Calibration_Retry_Count 0x0032   100   100   000    Old_age   Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       259
192 Power-Off_Retract_Count 0x0032   200   200   000    Old_age   Always       -       204
193 Load_Cycle_Count        0x0032   053   053   000    Old_age   Always       -       443158
194 Temperature_Celsius     0x0022   114   084   000    Old_age   Always       -       36
196 Reallocated_Event_Count 0x0032   001   001   000    Old_age   Always       -       421
197 Current_Pending_Sector  0x0032   199   197   000    Old_age   Always       -       537
198 Offline_Uncorrectable   0x0030   200   141   000    Old_age   Offline      -       290
199 UDMA_CRC_Error_Count    0x0032   200   181   000    Old_age   Always       -       209
200 Multi_Zone_Error_Rate   0x0008   122   001   000    Old_age   Offline      -       20879

SMART Error Log Version: 1
ATA Error Count: 51642 (device log contains only the most recent five errors)
    CR = Command Register [HEX]
    FR = Features Register [HEX]
    SC = Sector Count Register [HEX]
    SN = Sector Number Register [HEX]
    CL = Cylinder Low Register [HEX]
    CH = Cylinder High Register [HEX]
    DH = Device/Head Register [HEX]
    DC = Device Command Register [HEX]
    ER = Error register [HEX]
    ST = Status register [HEX]
Powered_Up_Time is measured from power on, and printed as
DDd+hh:mm:SS.sss where DD=days, hh=hours, mm=minutes,
SS=sec, and sss=millisec. It "wraps" after 49.710 days.

Error 51642 occurred at disk power-on lifetime: 28060 hours (1169 days + 4 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  04 61 02 00 00 00 a0  Device Fault; Error: ABRT

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  ef 10 02 00 00 00 a0 08  22d+07:01:03.463  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.458  IDENTIFY DEVICE
  ef 03 46 00 00 00 a0 08  22d+07:01:03.458  SET FEATURES [Set transfer mode]
  ef 10 02 00 00 00 a0 08  22d+07:01:03.458  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.453  IDENTIFY DEVICE

Error 51641 occurred at disk power-on lifetime: 28060 hours (1169 days + 4 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  04 61 46 00 00 00 a0  Device Fault; Error: ABRT

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  ef 03 46 00 00 00 a0 08  22d+07:01:03.458  SET FEATURES [Set transfer mode]
  ef 10 02 00 00 00 a0 08  22d+07:01:03.458  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.453  IDENTIFY DEVICE
  ef 10 02 00 00 00 a0 08  22d+07:01:03.453  SET FEATURES [Reserved for Serial ATA]

Error 51640 occurred at disk power-on lifetime: 28060 hours (1169 days + 4 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  04 61 02 00 00 00 a0  Device Fault; Error: ABRT

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  ef 10 02 00 00 00 a0 08  22d+07:01:03.458  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.453  IDENTIFY DEVICE
  ef 10 02 00 00 00 a0 08  22d+07:01:03.453  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.448  IDENTIFY DEVICE

Error 51639 occurred at disk power-on lifetime: 28060 hours (1169 days + 4 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  04 61 02 00 00 00 a0  Device Fault; Error: ABRT

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  ef 10 02 00 00 00 a0 08  22d+07:01:03.453  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.448  IDENTIFY DEVICE
  ef 03 46 00 00 00 a0 08  22d+07:01:03.448  SET FEATURES [Set transfer mode]
  ef 10 02 00 00 00 a0 08  22d+07:01:03.448  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.443  IDENTIFY DEVICE

Error 51638 occurred at disk power-on lifetime: 28060 hours (1169 days + 4 hours)
  When the command that caused the error occurred, the device was active or idle.

  After command completion occurred, registers were:
  ER ST SC SN CL CH DH
  -- -- -- -- -- -- --
  04 61 46 00 00 00 a0  Device Fault; Error: ABRT

  Commands leading to the command that caused the error were:
  CR FR SC SN CL CH DH DC   Powered_Up_Time  Command/Feature_Name
  -- -- -- -- -- -- -- --  ----------------  --------------------
  ef 03 46 00 00 00 a0 08  22d+07:01:03.448  SET FEATURES [Set transfer mode]
  ef 10 02 00 00 00 a0 08  22d+07:01:03.448  SET FEATURES [Reserved for Serial ATA]
  ec 00 00 00 00 00 a0 08  22d+07:01:03.443  IDENTIFY DEVICE
  ef 10 02 00 00 00 a0 08  22d+07:01:03.443  SET FEATURES [Reserved for Serial ATA]

SMART Self-test log structure revision number 1
No self-tests have been logged.  [To run self-tests, use: smartctl -t]


SMART Selective self-test log data structure revision number 1
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Not_testing
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.

ちなみに正常なときは

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x002f   200   200   051    Pre-fail  Always       -       0
  3 Spin_Up_Time            0x0027   181   167   021    Pre-fail  Always       -       5941
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       654
  5 Reallocated_Sector_Ct   0x0033   200   200   140    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x002e   200   200   000    Old_age   Always       -       0
  9 Power_On_Hours          0x0032   047   047   000    Old_age   Always       -       39322
 10 Spin_Retry_Count        0x0032   100   100   000    Old_age   Always       -       0
 11 Calibration_Retry_Count 0x0032   100   100   000    Old_age   Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       226
192 Power-Off_Retract_Count 0x0032   200   200   000    Old_age   Always       -       192
193 Load_Cycle_Count        0x0032   162   162   000    Old_age   Always       -       115939
194 Temperature_Celsius     0x0022   116   085   000    Old_age   Always       -       34
196 Reallocated_Event_Count 0x0032   200   200   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0032   200   200   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0030   200   200   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x0032   200   200   000    Old_age   Always       -       3
200 Multi_Zone_Error_Rate   0x0008   200   200   000    Old_age   Offline      -       0

こんな感じ。

エラーレートがこんな数字でも動くんだからHDDってすごい。

READメインディスクだし、別にどうってこと無い。RAIDでソコまで気にしなくても良いんだなぁって思う。限界まで行くぜ

RAID方式に変わる、HDD 式年遷宮方式

RAIDによるミラーリングは、メンテコストや初期投資、初期設定コストがかかるので、伊勢神宮式年遷宮と同様に、一定期間経過後に、HDDの中身を新しいHDDに丸ごとお引越しするHDD式年遷宮を、お手軽なバックアップとデータ担保の手法として名付けたい。

github で git コミットメッセージで issue 番号を指定

github のIssueとコミットを関連付ける

コミットメッセージで、Issueと関連付けるには

git commit -m "あれこれに追加 #1234"

このように#ISSUE番号を書くと関連付けて、Issueに関連付けられる

github issue をコミットで閉じる

git commit -m "あれこれ fix #1234"

このように fix #番号 でIssueに関連付けられ、Issueが閉じられる。

fix だけ?新機能の時はどうするの

git commit -m "あれこれ close #1234" 

このように close #番号 で issue に関連付けられる、Issueが閉じられる

一度に複数のIssueを片付けたら?

git commit -m "あれこれ close #1234 #1235 #1236 "

このように、番号を複数書くことが出来る

まとめ

コミットメッセージは

キーワード #num

閉じられる

キーワード一覧はコレ

  • close
  • closes
  • closed
  • fix
  • fixes
  • fixed
  • resolve
  • resolves
  • resolved

参考資料

Closing issues via commit messages - User Documentation

adduser/useradd するときのデフォルト設定(bash/zsh)やグループを設定する。

adduser した後にいちいちユーザーのグループを変えるのが面倒くさい。

そこで useradd -D を使うと基本設定を変えることが出来る。

takuya@:~$ useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no

デフォルトのシェルを変えるには

sudo useradd -D --shell=/bin/zsh

または

sudo useradd -D -s /bin/sh 

これでデフォルトのシェルを変えることが出来ます。

takuya@:~$ sudo useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no

所属するグループを設定する。

takuya@:~$ sudo useradd -D -g 1000

設定したものがこちら

takuya@:~$ sudo useradd -D
GROUP=1000
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no

これで/etc/skel にひな形を置けば完璧。できれば post-useradd みたいなシェルスクリプトがあると助かるんだけど。現在のところないようです

参考資料

http://www.thegeekstuff.com/2009/06/useradd-adduser-newuser-how-to-create-linux-users/

シンボリックリンク(symlink)にtouch すると時間が変わるのは link?それとも実体?

symbolic link に touch してもファイルの更新日が変わらない・・・

シンボリックリンクに touch したんですけど、ファイルの日付が変わりません。

takuya@:~$ ll  .bash_sample
lrwxrwxrwx 1 takuya takuya    7 2016-06-03 15:16 .bash_sample -> .bashrc
takuya@:~$ touch .bash_sample
takuya@:~$ ll  .bash_sample
lrwxrwxrwx 1 takuya takuya    7 2016-06-03 15:16 .bash_sample -> .bashrc

変わらない。。。何でだ。

調べたら、実体を変えるとのこと

stack overflow を見たら、ここ来る前にman 見ろ!!と書いてあった。すいません。

man に書いてあった。

     -h      If the file is a symbolic link, change the times of the link itself
              rather than the file that the link points to.
             Note that -h implies -c and thus will not create any new files.

ファイルがシンボリックリンクの時は、ファイルのリンク先ではなく、リンクファイルその物ズバリの日付を変えたい時に使う。-h では -c でファイルを作らないようにするから注意しろ。とのこと。

touch -h とすれば symlink の日付を変更できる。

なるほどやってみよう

takuya@:~$ ll .bash_sample
lrwxrwxrwx 1 takuya takuya    7 2016-06-03 15:16 .bash_sample -> .bashrc
takuya@:~$ touch .bash_sample
takuya@:~$ ll .bashrc .bash_sample
lrwxrwxrwx 1 takuya takuya    7 2016-06-03 15:20 .bash_sample -> .bashrc

おお!変わった。

これって気づかないとはまるよなぁ。

ls コマンドで表示されるタイムスタンプはmtime

linux のls コマンドが表示する時間は mtime

表題のとおりです。

takuya@~$ stat .ssh/id_rsa.pub
  File: '.ssh/id_rsa.pub' 
  Size: 58          Blocks: 8          IO Block: 4096   symbolic link
Device: 1000004h/16777220d  Inode: 38222423    Links: 1
Access: (0755/lrwxr-xr-x)  Uid: (  501/  takuya)   Gid: (   20/   staff)
Access: 2016-06-03 14:50:07.000000000 +0900
Modify: 2016-06-03 14:50:07.000000000 +0900
Change: 2016-06-03 14:50:07.000000000 +0900
 Birth: 2015-07-14 00:49:34.000000000 +0900

もし、mtime 以外の情報がほしい時は

  • 上記のように stat する。*1
  • ls にオプションをつける

ls のオプション

atime で表示

ls -lu  # atime / access time

ctime で表示

ls -lc  # ctime / change time

mtime で表示

ls -l  # mtime / modifed time

いちおう -U ってのもあるんだけどよくわからなかった。

実際にやってみた結果

takuya@:~$ stat .bash_profile
  File: `.bash_profile'
  Size: 193             Blocks: 8          IO Block: 4096   通常ファイル
Device: fd03h/64771d    Inode: 262274      Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/  takuya)   Gid: ( 1000/  takuya)
Access: 2016-06-03 14:25:51.919778755 +0900
Modify: 2015-11-20 14:02:30.000000000 +0900
Change: 2016-06-03 14:25:21.264778997 +0900
 Birth: -
takuya@:~$ ls -lu .bash_profile
-rw-r--r-- 1 takuya takuya 193 2016-06-03 14:25 .bash_profile
takuya@:~$ ls -lc .bash_profile
-rw-r--r-- 1 takuya takuya 193 2016-06-03 14:25 .bash_profile
takuya@:~$ ls -l .bash_profile
-rw-r--r-- 1 takuya takuya 193 2015-11-20 14:02 .bash_profile

参考資料

http://te2u.hatenablog.jp/entry/20090317/p1

man ls

-c      Use time when file status was last changed for sorting (-t) or long printing (-l).
-u      Use time of last access, instead of last modification of the file for sorting (-t) or long printing (-l).
-U      Use time of file creation, instead of last modification for sorting (-t) or long output (-l).

*1: lsattr と記憶違いして詰まった。

ssh-copy-id が失敗するので、調べたらまさかの結果

ssh-copy-id が失敗する。。。

takuya@~$ ssh-copy-id  192.168.2.1

/usr/local/bin/ssh-copy-id: ERROR: failed to open ID file '/Users/takuya/.ssh/id_rsa.spare': No such file or directory
    (to install the contents of '/Users/takuya/.ssh/id_rsa.spare.pub' anyway, look at the -f option)

以前、id_ras のスペアを作りかけてやめたんだが、それがどうも影響してるようで。

原因はファイルのタイムスタンプ

ssh-copy-id はまさか開けないような?と思ってダメ元で開けたら、中身がシェルスクリプトだった。まさかのまさか。

ssh-copy-id を見ると、次のようなことが書いてある。

DEFAULT_PUB_ID_FILE="$HOME/$(cd "$HOME" ; ls -t .ssh/id*.pub 2>/dev/null | grep -v -- '-cert.pub$' | head -n 1)"

ポイントはここ。

 ls -t .ssh/id*.pub

ここで、.ssh のなかみで 拡張子 pubを最終更新日順で取得していて、一番新しい物を使う。

まさかの最終更新日。

なんと、公開鍵を決めているのは、日付順だった。

てっきり、keychains から探して、id_rsa (秘密鍵)から公開鍵を生成してくるんだと思ってた。

解決方法

touch .ssh/id_つかいたい公開鍵.pub

なんともまあ。

scp でサーバのport 番号( ポート指定)して、ファイル転送

scp コマンドでポート指定をするには

scp -P [port]

大文字の P の後にポート番号を続けます。

http みたいにポート番号を指定できないか http://example.com:8080/ と思ったけど無理だった。

サンプル

### local file to remote 
scp -P 2222 ./2022-04-20.tgz  root@example.tld:/path/to/dir/
#### remote file to local
scp -P 2222 root@example.tld:/path/to/file  backup.tgz

リモートtoリモートはない。なので、ポートは常に一個ですね。

よく間違える(rsync/ssh/scp)

サーバーの listen ポートの設定はポートフォワーディングをしてたり、SSH踏み台を使ってない限り、ヤッパリめんどくさいのです。

SSH の場合

ssh 192.168.1.1:2222

SCPの場合

scp 192.168.1.1 -P 2222

rsync の場合

rsync --port 2222 192.168.1.1

全部違うの本当に困る。

scp の場合の特徴

じつは、他にポート番号を指定するオプションがあったりします。

scp には SSH オプションというのがあり

scp -o 'Port 2222' 192.168.1.1

このようにもかけます。

scp の場合の注意点

引数の順番が大切です。

scp -P 2222 local_file 192.18.1.1:~/path

scp でポート指定するとき引数の順番を適当にすると -P は解釈されません。

これはNG

scp  local_file 192.18.1.1:~/path -P 2222
scp  local_file -P 2222 192.18.1.1:~/path 

ただしくはこう

ssh -P 2222 $LOCAL $SERVER_IP:$SERVER_PATH

この辺のややこしさも。これもSCPがあまり使われつかわれてない理由なのかもしれませね。(あくまでわたしの身近なところだけですけどあまり使われない)

port のオプションは本当によく忘れてます。

2020-04-18

自分で後で見るときに検索にかからないので、記述を大幅に追記した。

あるコマンドが含まれるパッケージを探す。apt-file/dpkg

あるコマンドがどのパッケージに含まれるか探したい

  • このコマンド、どこからインストールされたの?
  • このコマンドをインストールするには何を入れたら良いの?

これらの疑問を解決するために2つのコマンドが有ります。また或るパッケージで入れたコマンドにどんなものが有るか知りたいとき。パッケージのファイルを知りたいときに使う。

このコマンドは「どこから」インストールされたの

インストールされているコマンドが、どこ由来か、Originを探す。どのパッケージに含まれるのかを知りたい時。

この場合は、インストール済みなので、インストール済みパッケージの中身を探せばいいです。

かと言って、全てのパッケージをlist up して for grep するのは面倒なので、ソレ専用のコマンドが用意されています

たとえば、bin/locate はどこから来たのか。

## ln されている場合があるのでrealpathする
apt-file search $(realpath $(which locate ))

それはインストール済みなのか

apt list $(apt-file search $(realpath $(which locate )) | cut -d":" -f 1 )

それは、どんなファイルを持つのか

dpkg -L plocate  | grep bin

例 lsusb がどのパッケージか

takuya@:~$ dpkg -S $(which lsusb)
usbutils: /usr/bin/lsusb

-S が思い出せない時は多少強引に

pkg -l | cut -d " " -f 3 | xargs -I@ dpkg -L @ | grep lsusb

逆に、あるパッケージに含まれるコマンドを知りたい

例 util-linuxに含まれるコマンド

dpkg -L util-linux | grep bin/

とすれば、コマンドが出てきます。

インストールしたいコマンドが含まれるパッケージがわからない。

未インストールの場合、dpkg で網羅することが出来ないので、 apt-file を使います。

sudo apt install apt-file

apt-file はapt-lineに含まれる*.debに含まれる、ファイル一覧を取得して、インデックスしてくれます。

takuya@:~$ apt-file search /bin/locate
atlc: /usr/bin/locatediff
locate: /usr/bin/locate.findutils

初回起動では、ファイル一覧を取得するのでちょっと時間がかかる。

あれ?このコマンドってなんだっけ

普段良く使ってるコマンドがどこから入ってるか調べるのに便利です。

util-linux関連はBSDmacOS X に含まれてないコマンドもあるのでアレレと思った時に調べるのに使っています。

参考資料

http://www.cyberciti.biz/howto/question/linux/dpkg-cheat-sheet.php

http://d.hatena.ne.jp/stakizawa/20080823/t1

2017-05-06

若干修正

ES/JavaScriptのthisとアロー演算子について知っておくべきこと

this. この便利でハマりどころの多い変数

Array.forEach / map 系 のthisArg が安定しない。

this 変数の紹介 this 変数の例

apply , call

window オブジェクト コールバック イベントハンドラ Array.forEach

個人的な結論 this はできるだけ避ける

調べたキッカケは Array.forEach

arr = ["A","B","C"]
arr.forEach(  function ( x ) { console.log ( this ) }  )

このthisとして this => [“A”,“B”,“C”] を期待したわけです。

でも、this = window

arr = ["A","B","C"]
arr.forEach(  function ( x ) { console.log ( this ) }  )
//=> Window
//=> Window
//=> Window

え?Windowなの?ちょっとまって。this 。そうか、そうだった。

"abc".replace( /a/, function(x){return this} )
//=>"[object Window]bc"

そういえばそうでした。this は関数の定義されたスコープから探されますよね。

this はその関数が実行(無名関数なら定義)されたスコープになる。

JSの変数はその実行スコープで決まる。

arr.forEach(  function ( x ) { console.log ( this ) }  ) // ここはWindowが実行するので this = window

実行主体がWindowなのでthis=window 、匿名関数なので定義されたタイミングでthis が決まる。

でもコレを見て欲しい(もう謎すぎてヤバイ)

アロー演算子と、function で指定し場合

f:id:takuya_1st:20160602152936j:plain:w400

実行環境は次の通り

f:id:takuya_1st:20160602153206j:plain:w300

ちなみに use strict すると動作が変わる

f:id:takuya_1st:20160602154225j:plain:w400

function の場合は use strict すれば次のような動作になる。

function を匿名関数で渡した場合

ソース thisArg use strict 結果(this参照先)
arr.forEach( function(x){console.log(this);} ) なし なし Window
arr.forEach( function(x){“use strict”; console.log(this);},arr ) arr なし arr
arr.forEach( function(x){“use strict”; console.log(this);} ) なし あり undefined
arr.forEach( function(x){“use strict”; console.log(this);},arr )) arr あり arr

function を アロー演算子で渡した場合

ソース thisArg use strict 結果
arr.forEach( (x)=>{console.log(this);} ) なし なし Window
arr.forEach( (x)=>{console.log(this);}, arr ) arr なし Window
arr.forEach( (x)=>{“use strict”;console.log(this);}) なし あり Window
arr.forEach( (x)=>{“use strict”;console.log(this);}, arr ) arr あり Window

アロー演算子ではすべてが window(グローバル)です

forEach した場合ね

なにこれ揺れすぎ

ていうか、アロー演算子は this の値を、オブジェクト定義から参照する。

forEach引数 で this の値を指定しても、実行してるスコープが window なので強制的に Window (グローバルオブジェクト)になる。

アロー演算子でのforEachでは再束縛が出来なくなってる。。。。

もうね、this使うなとしか言いようが無い。

結論 this 使うな

暴論しておきたい。

参考資料

thisArgs について

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this

this について

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

感想

無名関数のときに"use strict" した forEach で thisArg 無しならで undefined になる。これが個人的にはキッチリしてて嬉しいよね。いかにもuse strict っぽい。

アロー演算子の場合 this なかったら強制グローバルってのはどうも腑に落ちてこないというか。

コレクションでforEach中のthis は定義元のオブジェクトより、コレクション自身をしてして欲しいような気はする。

forEach がネストした時とか特に。

forEach が導入されて数年になるけど、あっさり thisArgs がなかったような扱いになってるのが寂しい所。

追記 2017-06-02

this が云々というより、thisArgs について語りたかった。アロー演算子の this はグローバルなので、 map( f , thisArg ) で thisArg を指定しても無視されるって話がメイン。

使うか使わないかとか、forEachの第三引数の話が使う使わないとか、this そのものの理解がとか、ブクコメに云々もについても言いたいことは、あるけれど 現状 use stricit してるかチェックを油断してるとまじthisめんどーってなる。コーディング規約が決まった同一社コードばかり見てるわけじゃないんで。油断するなよ的な、そんな話

lsusb でUSBの一覧を取得する

lsusb というコマンド

lsXXX といって色々なものをls 出来るコマンドが有ります。今回はUSBをls 出来るコマンドを知ったので、メモしておきます。

インストール

sudo apt install usbutils

使ってみた

takuya@:~$ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

まぁ、USBにナニも挿していないのでroot デバイスしかみえませんが。

mouse やキーボード、USBメモリなどがささっているとはっきりした表示が出て便利です。