bash 在運行腳本時刪除資料夾

bash 在運行腳本時刪除資料夾

我有一個腳本在資料夾中運行。如果命令失敗,我想刪除包含腳本的資料夾。那可能嗎?

編輯:根據評論,我拿出了我嘗試過的內容。

答案1

我給答案是因為我擔心有人會嘗試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.

答案2

是的你可以。

這就是將會發生的事情:

[root@server ~]# mkdir new&&cd new
[root@server new]# echo -e "#! /bin/bash\nrm -rf" >remove.sh
[root@server new]# cat remove.sh
#!/bin/bash
rm -rf ~/新
[root@伺服器新]# ls
刪除.sh
[root@server new]# bash remove.sh
[根@伺服器新的]# ls

(此處為空,所有檔案和目錄都被刪除,但在更改目錄之前我們仍在這個「新」資料夾中)
[根@伺服器新的]# 光碟 ..
[root@server ~]# ls new
ls:無法存取新的:沒有這樣的檔案或目錄

相關內容