有沒有辦法在終端機中執行某些命令之前設定警告?

有沒有辦法在終端機中執行某些命令之前設定警告?

有一些終端命令能夠非常有效地銷毀大量資料。喜歡:sudo rm -rf /*rm -rf /*。我想設定一個警告,每當輸入這些破壞性命令時就會顯示警告。像這樣的事情:

sudo rm -rf /*
Are you sure you want to remove all files from your root 
directory recursively? This operation will remove all files from the root 
directory, any mounted filesystems attached to it and essential operating 
system files. 
Are you sure you want to proceed? [Y/n]

rm -rf /*
Are you sure you want to remove all files owned by $USER 
recursively? This operation will remove all your files on the root 
filesystem and any filesystems mounted to it.
Are you sure you want to proceed? [Y/n]

如何編寫一個腳本來執行此操作?

答案1

rm有一個選項-i,每次刪除文件之前都會詢問。我認為這不是你想要的,因為它要求每一個如果您想遞歸刪除檔案(例如 git 儲存庫),則刪除檔案通常需要數百個確認。

您想要的可能是一個簡單的腳本,可以rm像這樣“替換”

#!/bin/bash
if [ "$(ls -l $1 | wc -l)" = "1" ]; then
  rm $1 $@
else
  echo "You are going to delete these ($(ls -l $1 | wc -l)) files/directories via shell globbing" 
  ls $1
  read -p "Do you really want to delete these files? [y/n]" yn
  if [ $yn = [Yy] ]; then
    rm $1 $@
  fi
fi

注意:您必須使用“rm FILE ARGUMENTS”等腳本。

該腳本會查看您是否使用 shell 通配符選擇多個文件(目錄),但如果只有一個文件,則刪除該文件。

相關內容