暇人の寝室
技術系の記事や読書・アニメの感想などを投稿します。
プログラミング
前回の続き。
https://ruffles95952367.wordpress.com/2019/09/20/php%e3%81%a7bash%e3%81%aels%e3%82%b3%e3%83%9e%e3%83%b3%e3%83%89%e3%82%92%e4%bd%9c%e6%88%90%e3%81%99%e3%82%8b1/
前回まではカレントディレクトリしか表示できなかった。
そのため今回は下記2点の機能追加を行った。
PHPの場合引数は「$argv」という配列から取ることができる。ただし配列の最初には実行スクリプトが入っているため、それを除外する必要がある。
また、後述するオプションも含まれるため、除外しておく。
// Exclude script name
$args = array_slice($argv,1);
// Exclude options
$target_dirs = array_filter($args,function($value){
return !preg_match('/^-/',$value);
});
あとは以前と同じ要領で表示するのみ。
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オプションを作成する。
※スクリプトはこちらに公開している。