In an interactive shell script I'd like to save the output of a command to a file like in
$ echo "Hello, World" > test.txt
but prevent test.txt to be overwritten if it already exists. So I thought it would be a good idea to use cp with it's interactive option (cp -i) to check if the target file exists. I tried this:
$ echo -n "Hello" | cp -i /dev/stdin test.txt
This writes "Hello" to test.txt if test.txt doesn't exist yet, but aborts copying if test.txt exists, as cp reads the answer to whether to overwrite or not from just that pipe.
$ cp -i <(echo "World") test.txt cp: overwrite 'test.txt'? y '/proc/self/fd/11' -> 'test.txt'
works as intended, cp seems to take the subprocess' filedesriptor as source and this is cp'ied to test.txt and I simply don't know why.
Any ideas or explanations or better ways to do it?