LoginSignup
0
0

More than 1 year has passed since last update.

Linuxのコマンドで最新のファイルだけ取得する方法

Last updated at Posted at 2022-06-28

Linuxのコマンドで最新のファイルだけ取得するコマンドのメモ。

コマンド

ls -rt | tail -n 1

lsコマンド

  • 機能
    ディレクトリの内容を標準出力に出力する

  • オプション

オプション 内容
-r 並び順を反転させる
-t ファイルを更新日が新しい順に表示する

これで、ファイルが更新日が古い順(古い→新しい)に並び替えられる

tailコマンド

  • 機能
    ファイルや標準入力の最後の部分を標準出力に出力する

  • オプション

オプション 内容
-n 出力する行数を指定する

-n 1で最新のファイルが1つ取得できる

使い方

データを復旧するコマンドのうち、「バックアップ用サーバーにSSH接続し、最新のdumpファイルを取得する」コマンドを作成する際に使用しました。

$command = '(ssh -i .ssh/id_rsa -o StrictHostKeyChecking=no -o ConnectTimeout=30 -p ' . $backupServerPort . ' ' .  $backupServerUser . '@' . $backupServerHost . ' ls -rt ' . self::BACKUP_SERVER_PATH . ' | tail -n 1) 2>&1';

(今回の内容とはズレるけど、~/.ssh/configに接続情報を登録しておくと、ssh接続部分はもっと簡潔に書ける。参考:https://qiita.com/passol78/items/2ad123e39efeb1a5286b

参考

https://lanchesters.site/linux-ls-new/
https://atmarkit.itmedia.co.jp/ait/articles/1606/27/news018.html
https://eng-entrance.com/linux-command-tail

0
0
0

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