Sometimes when I want to delete a file (from within a script), I will just delete it rather than checking if it exists first. So I do this:
$ rm "temp.txt" 2>/dev/null
Instead of this:
[ -f "temp.txt" ] && rm "temp.txt"
I just feel it's a waste of time to go and check if the file exists and return an exit code.
So, perhaps it's quicker to do it the first way, especially if most of the time, the file is likely to be present.
Are there any other advantages (or downsides) to do it one way or the other?
Am I wrong to think it will ever be quicker?
[ -f "temp.txt" ] && rm "temp.txt"
mean? i suppose you mean rm -f not just -f. And why rm twice. I don't see what you're getting at. And in *nix I thought it's single quotes not double quotes, though I see double quotes works(tested in knoppix).rm
is not aliased torm -i
, so an "Enter" is not necessary to dismiss the rm prompt. 2) I only have 1rm
in each case, so I don't know what you mean about usingrm
twice. 3)[ -f "temp.txt" ] && rm "temp.txt"
is to only runrm
if file exists, I do NOT mean[ rm -f "temp.txt" ] &&...
. 4) Double-quotes... I am just in the habit of always using Double-quotes ("...") to quote filenames because filenames may contain one or more embedded apostrophe ('). In this example, I could have used either.&&
. I am sure it was there when I was writing it, but I must have somehow lost it before posting.[
is generally a symlink to (or equivalent of)test
, so[ -f x ]
is equivalent totest -f x ]
, and the final]
is ignored. So the same command could be writtentest -f "temp.txt" && rm "temp.txt"