LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   zsh return 0 if script sourced not executed (https://www.linuxquestions.org/questions/linux-general-1/zsh-return-0-if-script-sourced-not-executed-473177/)

cs-cam 08-12-2006 02:42 AM

zsh return 0 if script sourced not executed
 
I'm working on extending a set of shell scripts, one of the originals has a ton of functions that I'd like to use in others, however sourcing it executes it and things get all messy from there. I added this to hopefully stop it at a certain point if it's not directly executed:
Code:

if [ "$(basename $0)" != "makepkg" ]; then
        return 0
fi

That works in bash where $0 is set to "bash" however the target shell is zsh which has $0 set to "makepkg".

Does anyone have any suggestions as to other ways I can get around this? I've checked the zshbuiltins manpage to see if there is any tricky ways around it but couldn't find anything useful and Google isn't much help as soon as the word "source" is included in the search :/

Any ideas would be greatly appreciated :)

ntubski 08-12-2006 10:53 AM

I think you want to set the option NO_FUNCTION_ARG_ZERO:

Code:

~/tmp% cat thing.sh                                                           
#! /bin/zsh

echo "0 = $0"
~/tmp% source thing.sh                                                       
0 = thing.sh
~/tmp% ./thing.sh                                                             
0 = ./thing.sh
~/tmp% setopt NO_FUNCTION_ARG_ZERO                                           
~/tmp% source thing.sh                                                       
0 = zsh
~/tmp% ./thing.sh                                                             
0 = ./thing.sh
~/tmp%

But doesn't zsh have all that cool autoloading stuff you can use for defining functions?

soggycornflake 08-12-2006 11:41 AM

Quote:

But doesn't zsh have all that cool autoloading stuff you can use for defining functions?
Indeed, but that's mainly intended for interactive use, rather than in scripts (though I suppose you can use it in a script as long as you run compinit etc).

Quote:

however sourcing it executes it and things get all messy from there.
If you're sourcing files, it's usually better to put everything in functions, so the code is only executed when the function is called.

Could you reverse the logic? E.g.

Code:

if [[ ${0:t} == makepkg ]]; then
        ... do whatever
else
        ... do something else
fi

Any good?

Note that you don't need to quote $variables in zsh (unless you set shwordsplit). Also, :t does the same job as basename without spawning another program.


All times are GMT -5. The time now is 05:26 AM.