Linuxコマンドラインとshellスクリプト(11)--入出力リダイレクト

3396 ワード

入力と出力の理解

  • リダイレクトエラーメッセージls -al badfile 2> test4
  • リダイレクトエラーとデータls -al test test2 test3 badtest 2> test6 1> test7#エラーはtest 6に入力され、通常のデータはtest 7
  • に表示される.
  • ls -al test test2 &> test8#標準エラーと標準入力をtest 8
  • にリダイレクト

    スクリプトで出力をリダイレクト

  • 標準エラーecho "This is an error message" >&2
  • にテキストを出力する.
  • は、execコマンドを使用してshellスクリプトに実行中に特定のファイル記述子
  • にリダイレクトするように伝えることができる.
    echo "This is the start of the script";
    echo "now redirecting all output to another location";
    
    exec 1> testout
    exec 2> testerror
    
    echo "This output should go to the testout file";
    echo "This output should go to the testerror file" >&2;
    

    スクリプトへの入力のリダイレクト

  • execコマンドを使用すると、stdINをLinuxシステム上のファイルにリダイレクトできます.
    file="/Users/chenhong/Desktop/shell_workspace/STD.sh";
    exec 0< $file
    count=1
    while read line
    do
            echo "Line $count:$line";
            count=$[ $count + 1 ];
    done

    独自のリダイレクトを作成

  • execコマンドを使用して、割当ファイル記述子
  • を出力することができる.
    exec 3>testout #   exec 3>>testout  
    echo "This shoud output the STDOUT";
    echo "This shoud output the &3" >&3;
  • ファイル記述子を閉じるには、特殊記号&-exec 3>&-
  • にリダイレクトします.

    開いているファイル記述子のリスト

  • 現在のプロセスのデフォルトファイル記述子lsof -a -p $$ -d 0,1,2
  • を表示する.

    コマンド出力のブロック

  • shellがnullファイルに出力データは保存されず、ls -al > /dev/null
  • が失われます.
  • は、cat /dev/null > testfile
  • を作成する前にファイルを削除することなく、既存のファイルのデータを迅速に削除することができる.

    メッセージの記録

  • teeコマンドは、パイプのTコネクタに相当します.stdINからのデータを2つの宛先に同時に送信します.一方の宛先はstdOUT、他方の宛先はteeコマンドラインで指定するファイル名date | tee testout
  • である.
  • デフォルトではteeは毎回ファイルを上書きし、ファイルを追加し、-a date | tee -a testout
  • を使用できます.