【发布时间】:2013-02-15 23:54:51
【问题描述】:
我想禁用rm,除非在某些情况下。我在.sh 文件中编写了一个名为remove 的函数,它通过了我在实际调用rm 之前想要强加的某些检查。但是,仍然可以进入终端并简单地调用rm 函数而不是使用remove。有没有办法禁用rm函数,除非被remove调用?我希望它就像rm 功能对登录终端的用户不“存在”一样,所有“存在”都是删除功能。
甚至可能更进一步,当用户调用rm 时,它会在屏幕上打印一条声明说使用remove。
作为一个更广泛的问题,有没有办法在某些情况下禁用终端命令?我知道我可以为 rm 创建一个别名来要求 root,但这是一种简单且不太方便的方法。
#!/bin/bash
function rm {
if [ $# -le 0 ]; then
echo "Error: no arguments specified."
else
hasDir=0
for arg in "$@"; do
if [ -d "$arg" ]; then hasDir=1; fi
done
ac="Action canceled."
resp=("y" "n" "e")
sure=" "
while [ "$sure" != "y" ] && [ "$sure" != "n" ]; do
read -p "PERMANENT ACTION. Are you sure? (y/n): " sure
done
if [ "$sure" == "n" ]; then echo "$ac"; return; fi
if [ $hasDir -eq 1 ]; then
direc=" "
validResp=0
while [ $validResp -eq 0 ]; do
read -p "Remove all sub-directories? (y/n/e): " direc
for ans in "${resp[@]}"; do
if [ "$direc" == "$ans" ]; then validResp=1; fi
done
done
if [ "$direc" == "e" ]; then echo "$ac"; return; fi
else
direc="n"
fi
check=" "
validResp=0
while [ $validResp -eq 0 ]; do
read -p "Verify removal of each file? (y/n): " check
for ans in "${resp[@]}"; do
if [ "$check" == "$ans" ]; then validResp=1; fi
done
done
if [ "$check" == "e" ]; then echo "$ac"; return; fi
if [ "$direc" == "n" ]; then
if [ "$check" == "n" ]; then
for file in "$@"; do
if [ ! -d "$file" ]; then command rm -f "$file"; fi
done
else
for file in "$@"; do
if [ ! -d "$file" ]; then command rm -i "$file"; fi
done
fi
else
if [ "$check" == "n" ]; then
command rm -rf "$@"
else
command rm -ir "$@"
fi
fi
fi
}
【问题讨论】:
-
我会担心所有那些你不知道使用
rm的脚本 - 来自cron和init*等。你能不能只是改变 PATH 让你的 @987654337 @ 首先它不会阻止人们做/bin/rmthough. -
rm是可执行文件,而不是 shell 命令或函数。请记住,除了bash之外,还有其他 shell。例如,运行zsh将绕过您尝试创建的任何基于 shell 的障碍。 -
问题是我无法命名我的函数
rm,因为它进入了递归状态。这就是为什么我必须给它取个别的名字,特别是remove。 -
我想这样做的原因不是出于安全原因或类似的原因,而只是为了能够做到这一点的知识。为了防止我不小心使用
rm哈哈。 -
在清理缩进时,我注意到您的脚本中似乎缺少
fi。
标签: linux bash ubuntu-12.04 rm