前回の続き。
前回まではカレントディレクトリしか表示できなかった。
そのため今回は下記2点の機能追加を行った。
- 引数で指定したディレクトリを表示する(複数指定可)
- -aオプションをつけた場合のみドットファイルを表示する
実装
引数で指定したディレクトリを表示する(複数指定可)
PHPの場合引数は「$argv」という配列から取ることができる。ただし配列の最初には実行スクリプトが入っているため、それを除外する必要がある。
また、後述するオプションも含まれるため、除外しておく。
// Exclude script name
$args = array_slice($argv,1);
// Exclude options
$target_dirs = array_filter($args,function($value){
return !preg_match('/^-/',$value);
});
あとは以前と同じ要領で表示するのみ。
-aオプションをつけた場合のみドットファイルを表示
PHPではオプションはgetopt()で取り出せる。
https://www.php.net/manual/ja/function.getopt.php
aオプションがない場合はドットファイルを除外するようにする。
$scan_dirs = scandir($target_dir);
// If 'a' is specified, it exclude dirs beginning with '.'.
if(!array_key_exists('a',$options)){
$scan_dirs = array_filter($scan_dirs,function($value){
return !preg_match('/^\.[^.]*/',$value);
});
}
動かしてみる
> cd test_dir
# 通常
> php ../ls.php .
test3 test4 %
# aオプション付き
> php ../ls.php -a .
. .. test3 test4 %
# 複数ディレクトリ
> php ../ls.php . ..
.:
test3 test4
..:
README.md ls.php test1 test2 test_dir %
# 複数ディレクトリ(aオプション)
> php ../ls.php -a . ..
.:
. .. test3 test4
..:
. .. .git README.md ls.php test1 test2 test_dir %
次回
-lオプションを作成する。
※スクリプトはhttps://github.com/ylafaro0310/php-lsに公開している。