2019年8月20日 星期二

[ Shell ] sourced?

A quick thought is using $0 and $_ as follow, but many exceptions.

    [ "$0" != "$_" ]  && echo Sourced

A better version to tell sourced condition, but still doesn't cover all cases.

    [ "$0" = "`ps p $$ o cmd=`" ] && echo Sourced

Finally a perfect solution, cheers!

    [ "`cat /proc/$$/cmdline`" = "$0" ] && echo Sourced

However /proc/$$/cmdline may contain zero characters and grep may not support -z option, so revised again, almost universal now.

    [ "`cat /proc/$$/cmdline | xargs -0 echo`" = "$0" ] && echo Sourced!

Under bash there is a quick way to exit without quitting the console:

    return X >&/dev/null || exit X

or

    eval "return X >&/dev/null; exit X"

Where X is the exit code, assume sourced and simply returns, if failed, do exit.

Form 2 is treated as an executive unit instead of two separate commands compared to form 1 and is useful in complicated conditions which form 1 won't work, says:

    [ ... ] && command 1 && command 2 && eval "return X >&/dev/null; exit X"

沒有留言:

張貼留言

[SSH & SCP] ignore known hosts

Host's key could be changed in many cases. It's a good idea to ignore host's key if no security issues. Add following options ...