Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question

2 Answers 2

up vote 3 down vote accepted

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
share|improve this answer
    
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 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 at 19:29
4  
Isn't -remount going to recurse indefinitely? –  Izkata Nov 25 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 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 at 22:34
#!/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^.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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