set -o noclobber

表題のビルトインコマンドについて。

■ 環境

  • bash
  • macOS High Sierra

■ set -o noclobber

リダイレクト(>)を使って標準出力をファイルに出力させることは多々あるのだが、誤ってファイルを上書きしてしまうケアレスミスが発生することがたまにある。だいたいは履歴のコマンドを再実行する際にやってしまう。

これを防ぐために表題を”.bashrc“に記載することにした。

set -o noclobber

もしくは下記でもOKなようである。

set -C

こうすることで、リダイレクト先のファイルが既に存在する場合には下記のようにエラーとなる。

$ ls
test
$
$ echo "test" > test
-bash: test: cannot overwrite existing file
$

>>“の追記でのリダイレクトの場合には問題なく書き込める。

ちなみに`man`には下記のような記載になっている。

Redirecting Output
  :
       If  the  redirection  operator is >, and the noclobber option to the set builtin has been enabled, the redirection
       will fail if the file whose name results from the expansion of word exists and is a regular file.   If  the  redi-
       rection  operator  is  >|, or the redirection operator is > and the noclobber option to the set builtin command is
       not enabled, the redirection is attempted even if the file named by word exists.
  :

以上。

コメントを残す

メールアドレスが公開されることはありません。

CAPTCHA


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください