0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シェルの「リダイレクト」使い方について

Last updated at Posted at 2025-05-01

目次

  • リダイレクトとは
  • 基本構文まとめ
  • よく使うリダイレクト例
  • 補足:ファイル記述子

リダイレクトとは

リダイレクトは、コマンドの出力(標準出力)やエラー(標準エラー出力)をファイルに保存したり、無視したりする操作のことです。
Linuxコマンドの出力やエラーを、次のようにファイルや他の出力先に流す(redirect) ことができます。

基本構文まとめ

構文 説明
> 標準出力をファイルへ(上書き
>> 標準出力をファイルへ(追記
2> 標準エラーをファイルへ(上書き
2>> 標準エラーをファイルへ(追記
2>&1 標準エラーを標準出力にまとめる

よく使うリダイレクト例

  • 標準出力をファイルへ保存
ls > result.txt

→ls の結果を result.txt に上書き保存
(すでにファイルがある場合は上書き)

  • ファイルに追記(消さずに追加)
echo "hello" >> log.txt

→log.txt の末尾に "hello" を追記

  • エラーメッセージをファイルに保存
ls not_exist_file 2> error.log

→標準エラー出力を error.log に出力(標準出力は無視)

  • 出力とエラーを同じファイルに保存
your_command > all.log 2>&1

→標準出力を all.log に保存
→標準エラーも標準出力に「リダイレクト」して同じファイルに保存

  • 出力を捨てる
your_command > /dev/null 2>&1

→出力もエラーも捨てる(完全に無視したいときに便利)

  • 応用:標準出力とエラーを分けて保存
your_command > out.log 2> err.log

→標準出力は out.log 、標準エラーは err.log に保存

補足:ファイル記述子

0:標準入力(stdin)
1:標準出力(stdout)
2:標準エラー出力(stderr)

2>&1は、「ファイル記述子2(stderr)をファイル記述子1(stdout)と同じ場所に送る」という意味です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?