使用 `case` 处理脚本参数

Pol*_*len 8 shell bash

我可以使用该case语句来处理参数吗?所以,使用 -restart 我想执行“-umount”和“-mount”

#!/bin/bash
case "$1" in
-mount
mount /ip/share1 /local/share1
;;
-umount
umount /ip/share1
;;
-restart
# echo TODO
;;
*)
[...]
esac
Run Code Online (Sandbox Code Playgroud)

Dop*_*oti 10

在我看来,这应该有效,除了缺少)s的语法狡辩。我对此进行了测试,它的行为正确..

#/bin/bash
case "$1" in
  "-mount")
    mount /path/to/device /path/to/mountpoint
    ;;
  "-unmount")
    umount /path/to/mountpoint
    ;;
  "-remount")
    "$0" -unmount
    "$0" -mount
    ;;
  *)
    echo "You have failed to specify what to do correctly."
    exit 1
    ;;
esac
Run Code Online (Sandbox Code Playgroud)

  • `-remount` 不会无限递归吗? (4认同)
  • 全部有效积分。我想我更多地关注使用“case..esac”来处理参数的问题。如果我正在编写这样的脚本,我也会更倾向于使用函数式路线。 (2认同)