linux 创建带参数的bash函数

jogvjijk  于 2023-04-05  发布在  Linux
关注(0)|答案(2)|浏览(149)

当我输入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
}
xlpyo6sf

xlpyo6sf1#

如果你不介意rm -frrm -r -f等不被捕获,这将工作得很好:

rm()
  if [[ $1 = -rf ]]; then
    read -p 'Are you sure? ' reply
    if [[ $reply = yes ]]; then
      command rm "$@"
    fi
  fi
gxwragnw

gxwragnw2#

让我们来看看。覆盖所有情况(-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 dirrm -f file(因此只能使用递归或强制,但不能组合使用)。

相关问题