LoginSignup
10
9

More than 5 years have passed since last update.

ShellScript で try-throw-catch-finally

Last updated at Posted at 2013-03-28

追記

全世界に<del>もしかしたら恥を</del>知らしめるためにも GitHub に上げました

git clone https://github.com/kaosf/shellscript-try-catch-finally
cd shellscript-try-catch-finally

で即座に試せます.


何もこんなことしなくても… とも思いますが.

run.sh
#! /bin/sh

finally() {
  RET=$?
  echo "return code: $RET"
  if [ $RET -ne 0 ]; then
                              #
    echo "ERROR!"             # here is 'catch' block
                              #
  else
    echo "no error (OK!)"
  fi
                              #
  echo "final process"        # here is 'finally' block
                              #
  exit $RET
}
set -e
trap finally EXIT
                              #
./a.sh                        # here is 'try' block
./b.sh                        # exit 1, exit 2, ... mean 'throw'
./c.sh                        #
a.sh
#! /bin/sh
echo 'a'
exit 0
b.sh
#! /bin/sh
echo 'b'
exit 1
c.sh
#! /bin/sh
echo 'c'
exit 0

./run.sh で走らせてみると…

a
b
return code: 1
ERROR!
final process

echo $? で終了コードを確かめてみると…

1

b.shexit 1exit 0 とか exit 2 とかに変えて試してみて下さい.

と言うより,そもそももっといい方法無いですか?Perl 使えとか Python 使えとかは無しでオネシャス (‘o‘)ノ

参考サイト

10
9
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9