我想在输入rm -rf
到终端时提示确认问题,如果回答"是"则执行操作。我在直接rm
命令中找到了这样的内容:
rm() {
read -p "Type password? " pass
if [ "$pass" = "1234" ]; then
command rm "$@"
else
#Termination and echo a message wrong pass.
fi
}
用于添加到。bashrc。并将其转换为:
rm(){
if [ $1 -eq "-" ] && [ $2 -eq "r" ] && [ $2 -eq "r" ]; then
read -p "Do you really want to delete?" ans
if [ ans -eq "yes" ]; then
rm -rf $@;
else
fi
else
fi
}
但我知道它不会工作。那么我如何检测rm -rf
命令并提示我的自定义确认问题?
编辑:我现在有这个,但仍然没有运气:
rm(){
if [ $1 = "-rf" ]; then
read -p "Do you really want to delete?" ans;
if [ $ans = "yes" ]; then
rm -rf "$@";
fi
fi
}
如果您不介意rm -fr
,rm -r -f
等不被捕获,这将工作得很好:
rm()
if [[ $1 = -rf ]]; then
read -p 'Are you sure? ' reply
if [[ $reply = yes ]]; then
command rm "$@"
fi
fi
让我们看看。要涵盖所有情况(-rf
,-fr
,-r -f
,--recursive --force
,-R --force
;或其他组合,例如-vrvfv
-getopts
可能有帮助)。
这里有一个函数可以让你开始。
rm() {
local use_force=0
local is_recursive=0
for arg; do
case "$arg" in
--force) use_force=1 ;;
--recursive) is_recursive=1 ;;
# skip remaining long options:
--*) continue ;;
# handle short options:
-*)
while getopts :frFR flag "$@"; do
case "$flag" in
[fF]) use_force=1 ;;
[rR]) is_recursive=1 ;;
esac
done
;;
esac
done
if [ "$use_force" = 1 ] && [ "$is_recursive" = 1 ]; then
read -p 'Do you really want to delete?' answer
case "$answer" in
[yY]*) command rm "$@" ;;
*) echo 'Skipping delete ...' ;;
esac
else
# only -f/--force, only -R/-r/--recursive, or neither
command rm "$@"
fi
}
你没有真正指定你想如何处理rm -r dir
或rm -f file
(所以只有递归或只有强制,而不是组合)。我假定在这种情况下您不会收到确认问题。