Memo

メモ > サーバ > 各論: コマンド > ファイル・ディレクトリ操作

■ファイル・ディレクトリ操作
■ディレクトリ移動
$ cd … ホームディレクトリへ移動 $ cd - … 直前のディレクトリへ移動
「cd」は「Change Directory」の略 作業ディレクトリを移動するcdコマンドの詳細まとめました【Linuxコマンド集】 https://eng-entrance.com/linux-command-cd ■ファイルやディレクトリを一覧表示
$ ls $ ls -l … 詳細情報とともに一覧表示(「ll」としても同様) $ ls -t … 修正時刻の昇順に一覧表示 $ ls -lt … 詳細情報とともに修正時刻の昇順に一覧表示(「ll -t」としても同様) $ ls -tr … 修正時刻の降順に一覧表示 $ ls -ltr … 詳細情報とともに修正時刻の降順に一覧表示(「ll -tr」としても同様)
「ls」は「List Segments」の略 lsコマンドの使い方と覚えたい15のオプション【Linuxコマンド集】 https://eng-entrance.com/linux_command_ls ■ファイルサイズを適当な単位で表示
$ ll 合計 72 -rwxrwxr-x 1 refirio refirio 6424 5月 4 21:49 2016 test -rw-rw-r-- 1 refirio refirio 82 5月 4 21:40 2016 test.c -rw-rw-r-- 1 refirio refirio 1504 5月 4 21:43 2016 test.o -rw-rw-r-- 1 refirio refirio 444 5月 4 21:41 2016 test.s $ ll -h 合計 72K -rwxrwxr-x 1 refirio refirio 6.3K 5月 4 21:49 2016 test -rw-rw-r-- 1 refirio refirio 82 5月 4 21:40 2016 test.c -rw-rw-r-- 1 refirio refirio 1.5K 5月 4 21:43 2016 test.o -rw-rw-r-- 1 refirio refirio 444 5月 4 21:41 2016 test.s
■ファイルの表示
$ vim test.txt … Vimを起動 $ vi test.txt … 大抵の環境ではVimが立ち上がる $ view test.txt … Vimの読み取り専用モードで表示(Vimの行番号やカラースキーマが適用される) $ cat test.txt … 内容をすべて表示 $ more test.txt … スペースキーで1ページずつ表示 $ less test.txt … ↑↓で1行ずつ表示。スペースキーで1ページずつ表示
Linuxでテキストファイルを閲覧できるコマンドにはいろいろあるよ - 無理しない感じ http://hogesuke.hateblo.jp/entry/2014/04/08/041951 コマンド less ファイル表示プログラム (ページャ) http://x68000.q-e-d.net/~68user/unix/pickup?less インフラエンジニアとしてよく使うコマンド集 http://qiita.com/sion_cojp/items/04a2aa76a1021fe77079 ■ファイルを作成
$ touch test.txt … test.txt を作成 $ touch `date +%Y%m%d_%H-%M-%S`.txt … 日時をファイル名としたファイル(20160905_13-26-19.txt など)を作成
以下のようにcatを使えば、ファイルの内容を指定して新規作成できる ただしインデントの制御が完全ではなかったり、変数展開されたりなどがある あくまでも簡易な手段として使える程度のものとなりそう
$ cat <<EOF > test.txt … ファイルをまるごと書き換える ABCDEFG HIJKLMN EOF $ cat <<EOF >> test.txt … ファイルの末尾に追加して書き込む OPQRSTU VWXYZ EOF
catコマンドでファイルに書き込みをする | ハックノート https://hacknote.jp/archives/13756/ 知ると便利なヒアドキュメント - Qiita https://qiita.com/kite_999/items/e77fb521fc39454244e7 ■ファイルを複製
$ cp test1.txt test2.txt $ cp -rp test1.txt test2.txt … pオプションも付けると、コピー元の所有者ID、グループID、アクセス権、最終更新日時、最終アクセス日時をコピー元と同じにしてコピーする
■ファイル名を変更(ファイルを移動)
$ mv test1.txt test2.txt
■ファイルを一括移動
$ mv /var/www/vhosts/xxx/html/* /var/www/vhosts/yyy/html
■ファイルを削除
$ rm test.txt … test.txt を削除 $ rm test_*.txt … ワイルドカードで一括削除 $ rm -f test_*.txt … 確認なしに削除
■ファイルをカラにする
$ cp /dev/null lsyncd.log
既存のファイルを空にするLinuxコマンド - Qiita https://qiita.com/nabewata07/items/e67d008a1f10429bb3bf ■ファイルのタイムスタンプを変更
$ touch -t 201504201230 test.txt … test.txtのタイムスタンプを2015年4月20日の12:30に設定
■ファイルを検索
$ find ./ -type f -print | xargs grep 'ABC' … 文字列「ABC」が含まれるファイルを表示 $ find ./ -name test.txt -ls … ファイル名が「test.txt」のファイルを検索 $ find ./ -name test* -ls … ファイル名が「test」から始まるファイルを検索 # find / -name php.ini … 「php.ini」ファイルの場所を表示
findコマンドの使い方: UNIX/Linuxの部屋 http://x68000.q-e-d.net/~68user/unix/pickup?find xargsでfindの結果をgrepに渡している https://hydrocul.github.io/wiki/commands/xargs.html findコマンドの使い方を簡単に理解するための7つのルール+実践的な知識 #Linux - Qiita https://qiita.com/ko1nksm/items/7fec71f78a394a80ed2b 以下のように、grepでもファイルを検索できる rでディレクトリから検索、Eで正規表現、iで大文字小文字を区別しない
$ grep -r "検索したい文字" ./ $ grep -r -i -E "正規表現で検索したい文字" ./
以下のようにすると 「extends Controller」を含むファイルの一覧から、「Carbon」を含むファイル一覧を表示 となる(要検証)
$ find ./ -type f -print | xargs grep "extends Controller" -l | xargs grep "Carbon" -l
以下はさらに拡張子でも絞り込んだ例
$ find ./ -type f -name "*.php" | xargs grep "extends Controller" -l | xargs grep "Carbon" -l
逆引きUNIXコマンド/grepでパターンヒットがあったファイルのファイル名のみ表示する方法 - Linuxと過ごす https://linux.just4fun.biz/?%E9%80%86%E5%BC%95%E3%81%8DUNIX%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89/grep... find http://codezine.jp/unixdic/w/find 【linux】更新日が最近のファイルを見つける(findコマンド) https://www.softel.co.jp/blogs/tech/archives/1332 【Linux】複数あるファイルの中から特定の文字列を検索するコマンド http://kawatama.net/web/1141 お仕事で知っておけば便利。コマンドを叩くだけで使えるワンライナーチートシート http://qiita.com/taiyop/items/bfeeb41259cb0d083d88 The Silver Searcher のススメ http://qiita.com/thermes/items/e1e0c94e2875df96921c 検索対象のディレクトリを複数指定したり、ワイルドカードで指定したりもできる 以下は7月10日のログディレクトリから「太郎」という文字を含むファイルを探す例
# find 20180710/ -type f -print | xargs grep '太郎'
以下のようにすると、20180710〜20180713を対象にできる(個別に指定する例)
# find 20180710/ 20180711/ 20180712/ 20180713/ -type f -print | xargs grep '太郎'
以下のようにすると、20180710〜20180719を対象にできる(ワイルドカードで指定する例)
# find 2018071*/ -type f -print | xargs grep '太郎'
以下のようにすると、ファイルの更新日時をもとに検索できる
$ find ./ -mtime -11 -ls … 更新日が10日以内のファイルを表示 $ find ./ -mtime +7 -and -mtime -15 -ls … 更新日が一週間前より古くて二週間前より新しい
mtimeはファイルの更新日時 ctimeはファイル名やパーミッションなども含めた更新日時 UNIXの部屋 コマンド: タイムスタンプ http://x68000.q-e-d.net/~68user/unix/pickup?%A5%BF%A5%A4%A5%E0%A5%B9%A5%BF%A5%F3%A5%D7 -11 ... 10日以内 +10 ... 10日以前 10 ... 10日前 +365 ... 一年間更新されていない -8 ... 一週間以内に変更された 7 ... 一週間前に更新された ■ファイルを検索(Perl) 複数ワードでファイル内全文をAND検索など、コマンドの組み合わせで難しいものはPerlで検索スクリプトを書くといい http://refirio.org/view/349 以下はプログラムの一例
################################################## #ファイル内検索プログラム ################################################## use strict; print 'Search words: '; my $input = <STDIN>; chop($input); &search('./', $input); exit; ### 再帰検索 sub search { my($dir, $word) = @_; # 半角スペース区切りで検索ワードを取得 my @keywords = split(/\s+/, $word); # 検索対象ディレクトリを開く my @dir; if (opendir(DIR, $dir)) { @dir = sort { $a cmp $b } readdir(DIR); closedir(DIR); } else { print "Can't open target directory: $dir\n"; } # 対象を順に検索 foreach my $file (@dir) { if ($file eq '.' or $file eq '..') { next; } my $target = "$dir$file"; if (-d $target) { # 対象がディレクトリなら再帰検索 &search("$target/", $word); } else { # 対象がファイルなら全文検索 my %hits; if (open(FH, $target)) { while (my $line = <FH>) { foreach my $keyword (@keywords) { if (index(lc($line), lc($keyword)) >= 0) { $hits{$keyword} = 1; } } } close(FH); } else { print "Can't read target file: $target\n"; } # AND検索チェック my $flag = 1; foreach my $keyword (@keywords) { if (!$hits{$keyword}) { $flag = 0; } } # 検索結果に表示 if ($flag) { print $target . "\n"; } } } return; }
例えば「search.pl」という名前で保存した場合、以下で検索できる
$ perl search.pl
■ディスク使用量を確認
# df … ディスク使用量を確認 ファイルシス 1K-ブロック 使用 使用可 使用% マウント位置 devtmpfs 485216 0 485216 0% /dev tmpfs 503468 0 503468 0% /dev/shm tmpfs 503468 412 503056 1% /run tmpfs 503468 0 503468 0% /sys/fs/cgroup /dev/xvda1 12570604 4890012 7680592 39% / tmpfs 100696 0 100696 0% /run/user/1000 # df -h … ディスク使用量を確認(見やすい単位で表示) ファイルシス サイズ 使用 残り 使用% マウント位置 devtmpfs 474M 0 474M 0% /dev tmpfs 492M 0 492M 0% /dev/shm tmpfs 492M 412K 492M 1% /run tmpfs 492M 0 492M 0% /sys/fs/cgroup /dev/xvda1 12G 4.7G 7.4G 39% / tmpfs 99M 0 99M 0% /run/user/1000 # lsblk … 利用できるブロックデバイスを一覧表示 NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvda 202:0 0 12G 0 disk └─xvda1 202:1 0 12G 0 part /
【 df 】コマンド――ディスクの空き領域を表示する:Linux基本コマンドTips(58) - @IT https://atmarkit.itmedia.co.jp/ait/articles/1610/24/news017.html 【 lsblk 】コマンド――ブロックデバイスを一覧表示する:Linux基本コマンドTips(180) - @IT https://atmarkit.itmedia.co.jp/ait/articles/1802/02/news021.html xvda(xvda1)がデータを恒久的に保存するストレージ領域。この「xvda」という名前は、OSが勝手に付ける名前 それ以外は「tmp」と付いているように一時的な領域。メモリ上にディスクを作成することにより、一時的な高速ストレージとして使用する ストレージデバイス(ブロックストレージ)|ほげほげテクノロジー|note https://note.com/tech_share/n/nb93761a67477 [Linux] メモリ上に高速なディスクを作成する - tmpfs https://blog.katsubemakito.net/linux/ramdisk-tmpfs Linuxのファイルシステムについて勉強したメモ - Qiita https://qiita.com/toshihirock/items/ca717f8ad9c66ced4047 xvdaの名前は、「xvd」と「a」により成り立っている よって複数のストレージを接続すると、「xvdb」「xvdc」などの名前になるみたい 「xvd」は「Xen Virtual block Device」から来た名前で、「Xen(仮想化フレームワーク)によるVirtual Block Device(仮想ブロックデバイス)」の略 第12章 DRBDとXenの使用 https://blog.drbd.jp/drbd-users-guide-8.4/ch-xen.html mount - 「/ dev / xvda1」デバイスとは何ですか? https://www.it-mure.jp.net/ja/mount/%E3%80%8C-dev-xvda1%E3%80%8D%E3%83%87%E3%83%90%E3%82%A4%E3%82%B9... ■ファイル数とディレクトリ数を数える
$ ls -laR | grep -c '^-' … 合計ファイル数 $ ls -laR | egrep -c '^d.+[^.]$' … 合計ディレクトリ数
あるディレクトリ以下の合計ファイル数を再帰的に知るunixコマンド http://logic.moo.jp/data/archives/336.html ■ファイルをサイズ順にソートして表示
# ll -S … ファイルサイズが大きいものから表示 # ll -Sr … ファイルサイズが小さいものから表示
■サイズの大きいファイルを検索
# du -s /* | sort -nr … ストレージサイズの大きい領域を表示 4194312 /mnt … メモリのスワップに4GBを割り当てている場合(単位はKBで表示される) 1281572 /usr 616296 /var 142244 /lib 62628 /boot
以下のようにして、容量を圧迫している箇所を探っていく
# du -s /* | sort -nr # du -s /var/* | sort -nr # du -s /var/www/* | sort -nr # du -s /var/www/html/* | sort -nr
以下のように -h をつけると、ファイルサイズを適当な単位で表示してくれる
# du -sh /* | sort -nr # ll -h /var/www/html
■ディレクトリ構成を tree 風に表示する
$ pwd;find . | sort | sed '1d;s/^\.//;s/\/\([^/]*\)$/|--\1/;s/\/[^/|]*/| /g'
tree コマンドが無い環境で tree コマンドを実現 - Qiita https://qiita.com/yone098@github/items/bba8a42de6b06e40983b ディレクトリ構成を tree 形式に表示する - Qiita https://qiita.com/hide/items/9a2876486b975e77b9c0 ■所有者と権限を変更
# chown apache /var/www/html/test … ディレクトリの所有者をapacheに変更 # chown -hR apache /var/www/html/test … ディレクトリの所有者をapacheに変更(再帰的) # chgrp apache /var/www/html/test … ディレクトリのグループをapacheに変更 # chgrp -hR apache /var/www/html/test … ディレクトリのグループをapacheに変更(再帰的) # chown apache. /var/www/html/test … ディレクトリの所有者とグループをapacheに変更 # chown apache:apache /var/www/html/test … 上と同じ # chown -hR apache. /var/www/html/test … ディレクトリの所有者とグループをapacheに変更(再帰的) # chown -hR apache:apache /var/www/html/test … 上と同じ # chmod 775 /var/www/html/test … 権限を775に変更 # chmod -R 775 /var/www/html/test … 権限を775に変更(再帰的) # find /var/www/html/test -type d -print | xargs chmod 775 … ディレクトリのみ権限を775に変更(再帰的) # find /var/www/html/test -type f -print | xargs chmod 664 … ファイルのみ権限を664に変更(再帰的)
Linuxコマンド【 chown 】ファイルの所有者やグループを変更 - Linux入門 - Webkaru https://webkaru.net/linux/chown-command/ find + chmodでパーミッションの一括変更 http://ext.omo3.com/webmaster/chmod.html ■ファイル作成時の所属グループを、親ディレクトリのグループにする 以下のようにして、スティッキービットを設定する
# chmod g+s /var/www/html/test
ファイル作成時の所属グループを、ディレクトリのグループに設定する http://qiita.com/ritukiii/items/bbb34c372ce35ec55679 setuid、setgid、およびスティッキービットを使用する特殊なファイルアクセス権 - Oracle Solaris 11.2 でのファイルのセキュリティー保護とファイル整合性の検証 https://docs.oracle.com/cd/E56342_01/html/E53949/secfile-69.html ■ファイル作成時の初期パーミッションを変更する とあるユーザのファイル作成時の初期パーミッションが644だとして、これを例えば664などに変更できる 0002 は 002 という指定でもいい
$ umask 0002 … 設定 $ umask … 確認 0002
希望の値は、ファイルは 666 から、ディレクトリは 777 からデフォルトのアクセス権を引けば求められる 例えばデフォルトのファイルパーミッションを 664 にしたい場合、 666 - 664 = 002 となり、002 もしくは 0002 と設定すればいいことが判る ただし、この設定はSSH接続を切断すると初期化されてしまうので注意 umask の値は、ログイン時に読み込まれる /etc/profile で指定されているので、ここを編集すれば恒久的に変更できる
# vi /etc/profile
if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then umask 002 else #umask 022 umask 002 fi
uidが200以上か否かで umask の値が変わるが、 上記のように変更するとすべてのユーザのファイル作成の初期パーミッションが644から664になる デフォルトのアクセス権 - umask https://kazmax.zpp.jp/linux_beginner/default_permission.html デフォルトのパーミッション設定: umask | 知識の箱 http://www.rivhiro-weather.com/knowledge/?p=168 ファイルやディレクトリ作成時の初期パーミッション設定を変えたい〜umask〜 - ITmedia エンタープライズ https://www.itmedia.co.jp/help/tips/linux/l0353.html umaskのデフォルト値 (CentOS6.4) - Web Application Security Memo https://www.pupha.net/archives/151/ umaskはどこで設定されている? | VPSサーバーでWebサイト公開 備忘録 ~Linux、MySQLからAJAXまで http://wordpress.honobono-life.info/lin-base/umask%E3%81%AF%E3%81%A9%E3%81%93%E3%81%A7%E8%A8%AD%E5%A... umask の初期設定を全部のユーザーに適用する - それマグで! https://takuya-1st.hatenablog.jp/entry/2018/02/13/190949 ■ディレクトリを作成
$ mkdir test … ディレクトリを作成 $ mkdir -p test/abc … 複数階層のディレクトリを作成 $ cd $_ … 作成したディレクトリに移動
「$_」で、ひとつ前に実行したコマンドラインの最後の引数を参照できる もしくは、「ESC → .」で直前のコマンドの最後のパラメータを補完できる [小ネタ] mkdir したディレクトリに cd する方法 9 選 +1 (BASH) | Developers.IO http://dev.classmethod.jp/etc/make-and-cd-patterns/ ■ディレクトリ名を変更
$ mv test1 test2
■ディレクトリを複製
$ cp test test_backup … 「cp: omitting directory `test'」と表示され、コピーできない $ cp -r test test_backup … ディレクトリをコピーする際は「r」オプションを付ける $ cp -rp test test_backup … pオプションも付けると、コピー元の所有者ID、グループID、アクセス権、最終更新日時、最終アクセス日時をコピー元と同じにしてコピーする $ cp -rp test/* /test_backup/ ... 隠しファイルや隠しフォルダはコピー対象にならない $ cp -rp test/. /test_backup/ ... 隠しファイルや隠しフォルダもコピー対象になる
以下は使用例
$ cp -rp /var/www/vhosts/xxx/html/phpmyadmin /var/www/vhosts/yyy/html
cpコマンドで不可視ファイルまでコピーする - Qiita https://qiita.com/sayama0402/items/cdf7debc9784ebac0115 ■ディレクトリを複製(特定ディレクトリを除外) cpでは特定ディレクトリのみ除外して複製することはできないが、rsyncを使えば可能 普通に複製する場合、以下のようにする
$ rsync -a /var/www/vhosts/test/ /var/www/vhosts/test_backup/
/var/www/vhosts/test/ を /var/www/vhosts/test_backup/ に複製するが、 /var/www/vhosts/test/blog/ は除外したい場合、以下のようにする(除外設定は、複製元のパスを基準に指定する)
$ rsync -a /var/www/vhosts/test/ /var/www/vhosts/test_backup/ --exclude '/blog/'
【linux】特定のディレクトリを除いてコピーしたい https://www.softel.co.jp/blogs/tech/archives/5267 ■ディレクトリを移動
$ mv /var/www/vhosts/terraport/html/deploy /var/www/vhosts/main/html $ mv target/ ../ … 一階層上に移動
■ディレクトリを削除
$ rm -rf ディレクトリ名 $ rm -rf 201603* … ワイルドカードで一括削除 $ rm -rf 20160[3-8]* … 正規表現で一括削除
r ... 中身のファイルも含めてディレクトリごと削除 f ... 確認なしに削除 ■ファイルを圧縮&展開
$ tar zcvf compress.tar.gz file1 file2 … TAR+GZIP形式で圧縮 $ gzip -dc compress.tar.gz | tar xvf … TAR+GZIP形式で展開 $ zip compress.zip file1 file2 … ZIP形式で圧縮 $ zip 201909.zip 201909*.jpg … ZIP形式で圧縮(正規表現で指定して圧縮) $ zip -r compress.zip directory … ZIP形式で圧縮(ディレクトリを再帰的に圧縮) $ unzip compress.zip … ZIP形式で展開
展開後、所有者と権限を調整する場合の例
# chown -R apache compress … 所有者をapacheに変更(再帰的) # find compress -type d -print | xargs chmod 775 … ディレクトリの権限を775に変更(再帰的) # find compress -type f -print | xargs chmod 664 … ファイルの権限を664に変更(再帰的)
古いログを削除する前にバックアップする場合の例
# cd /var/log/command/xxx … 作業ディレクトリへ移動 # zip -r 2016.zip 2016*/ … 「2016」から始まるディレクトリを1つに圧縮 # rm -rf 2016*/ … 「2016」から始まるディレクトリを削除
特定のディレクトリを除外して圧縮
$ zip -r example.zip example/ … ZIP形式でディレクトリを圧縮 $ zip -r example.zip example/ -x example/monitor/\* … ZIP形式でディレクトリを圧縮(monitorを除外) $ zip -r example.zip example/ -x example/monitor/\* example/switch/\* … ZIP形式でディレクトリを圧縮(monitorとswitchを除外)
tarで圧縮する時に特定のディレクトリは除外する方法 - ex1-lab https://ex1.m-yabe.com/archives/2145 カゲンぱぱのイイカゲンメモ帳: linuxのzipコマンドで特定フォルダーとファイルを除外する http://kagen88.blogspot.jp/2012/12/linuxzip.html ■ファイルを暗号化&復号化
$ openssl enc -e -aes128 -in plain.txt -out crypted.txt … 暗号化 $ openssl enc -d -aes128 -in crypted.txt -out plain.txt … 復号化
opensslコマンドの使い方: UNIX/Linuxの部屋 http://x68000.q-e-d.net/~68user/unix/pickup?openssl OpenSSLでファイルの暗号化・複合化するための備忘録 - Qiita https://qiita.com/Yarimizu14/items/49690c141b62507e00d9 opensslコマンドで簡単なファイル暗号化 - Qiita https://qiita.com/ikuwow/items/1cdb057352c06fd3d727 ■ファイルを比較
$ diff config.default.php config.php … ファイルを比較 $ diff -u config.default.php config.php … git風にファイルを比較 $ diff -ybBw config.default.php config.php … WinMerge風にファイルを比較
diffコマンドを便利に使う | bacchi.me https://bacchi.me/linux/diff-tips/

Advertisement