7

Can I use the case statement to handle arguments? So, using -restart I'd like execute "-umount" and "-mount"

#!/bin/bash
case "$1" in
-mount
mount /ip/share1 /local/share1
;;
-umount
umount /ip/share1
;;
-restart
# echo TODO
;;
*)
[...]
esac
9

It looks to me like that should work, other than the syntactical quibble of missing )s. I tested this and it behaves correctly..

#/bin/bash
case "$1" in
  "-mount")
    mount /path/to/device /path/to/mountpoint
    ;;
  "-unmount")
    umount /path/to/mountpoint
    ;;
  "-mount")
    "$0" -unmount
    "$0" -remount
    ;;
  *)
    echo "You have failed to specify what to do correctly."
    exit 1
    ;;
esac
  • Not good solution: inside "-remount" I don't want rewrite same code of "-mount" and "-umount" (the code above is only an example - real code is more than long). Thanks for help! :-) – Pol Hallen Nov 25 '14 at 19:24
  • 1
    $0 is the zeroth paramater to a script or function; in this case, the invocation of the script itself. If I invoke a script with ./script foo bar; $0 is "./script", $1 is "foo", and $2 is "bar". – DopeGhoti Nov 25 '14 at 19:29
  • 4
    Isn't -remount going to recurse indefinitely? – Izkata Nov 25 '14 at 21:25
  • 1
    in remount you want to: shift ; $0 -unmount "$@" ; $0 -mount "$@" ;; (... so you don t loop on -remount, and you also pass along any remaining parameters) – Olivier Dulac Nov 25 '14 at 23:50
  • 1
    Valid points all. I suppose I was concentrating more on the question of using case..esac to handle arguments at all. I too would be more inclined to use the functional route if I were authoring such a script. – DopeGhoti Nov 26 '14 at 22:34
3
#!/bin/bash
unset u
mnt() { ${u+u}mount /ip/share1 ${u-"/local/share1"}; }
case "$1"   in
(-mount)            :;; 
(-umount)  u=        ;;
(-restart) u= mnt    ;;
(*)               ! :;;
esac && mnt

You could use a function as ^above^.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.