bash 在运行脚本时删除文件夹

use*_*042 0 bash rm

我有一个脚本在文件夹中运行。如果命令失败,我想删除包含脚本的文件夹。那可能吗?

编辑:根据评论,我拿出了我尝试过的内容。

Oli*_*lac 5

我给出答案是因为我担心有人会尝试OP的建议......

一个重要的警告:问题中显示的脚本删除了 给出的目录pwd,该目录不是脚本所在的目录,而是启动脚本时用户所在的目录

如果有人这样做:(**不要尝试这个**)cd ; /path/to/thatscript他们会删除用户的整个主目录(因为“cd”返回到它)以及下面的所有内容!...

(这在某些 root 的 homedir 是“/”...的操作系统上尤其糟糕)。

相反,在您的脚本中您应该:

mydir="$(cd -P "$(dirname "$0");pwd)"     
      #retrieve the script's absolute path, 
      #even if the script was called via ../relative/path/to/script
echo "the script '$0' is in: ${mydir} "
...
# and then (if you really want this.... but I think it's a bad idea!)
# rm -rf "${mydir:-/tmp/__UNDEFINED__}"  #deletes ${mydir}, if defined
# once you're sure it is correctly reflecting the real script's directory.
Run Code Online (Sandbox Code Playgroud)