shell script to remove a file if it already exist

前端 未结 7 1099
面向向阳花
面向向阳花 2021-01-30 15:43

I am working on some stuff where I am storing data in a file. But each time I run the script it gets appended to the previous file.

I want help on how I can remove the f

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 15:53

    Don't bother checking if the file exists, just try to remove it.

    rm -f /p/a/t/h
    # or
    rm /p/a/t/h 2> /dev/null
    

    Note that the second command will fail (return a non-zero exit status) if the file did not exist, but the first will succeed owing to the -f (short for --force) option. Depending on the situation, this may be an important detail.

    But more likely, if you are appending to the file it is because your script is using >> to redirect something into the file. Just replace >> with >. It's hard to say since you've provided no code.

    Note that you can do something like test -f /p/a/t/h && rm /p/a/t/h, but doing so is completely pointless. It is quite possible that the test will return true but the /p/a/t/h will fail to exist before you try to remove it, or worse the test will fail and the /p/a/t/h will be created before you execute the next command which expects it to not exist. Attempting this is a classic race condition. Don't do it.

提交回复
热议问题