Sourabh Sourabh - 5 months ago 17
Linux Question

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.

Now 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?


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