开发者

Output redirect in shell to another file iff the file exist

I am using the following command to redirect the output to another file.

ls -l >>foo.txt

This command will append the output of ls -l to foo.txt. And if the file does not exist it will create a new file foo.txt and redirect the output to new foo.txt.

开发者_如何学CNow is there any way to redirect/append the output of ls -l to a file if it and only if the file already exist and otherwise it won't redirect the output or will discard it.

For my case if the foo.txt already exist it will append the output to foo.txt otherwise it will discard the output.

Is there any command to do this?


ls -l |
    if [ -f "$file" ]
        then cat >> "$file"
        else cat # or whatever you want to do with the output
    fi

Note that the operation is not atomic: it is possible to unlink the file after its existence is checked and before it's opened for writing.


Don't know any built-in syntax to do it but something like the following should work:

if [ -f foo.txt ] ; then
  out=foo.txt
else
  out=/dev/null
fi
ls -l >> $out


Tests if foo.txt exists and is a regular file before running the ls -l >> foo.txt command:

test -f foo.txt && ls -l >> foo.txt
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜