1827595 Members
3097 Online
109966 Solutions
New Discussion

Korn Shell question

 
SOLVED
Go to solution
Quark
Valued Contributor

Korn Shell question

Hi,

how do I exit a script from a function that is called as var=$()?
The following example always prints "x: 1" whereas I would expect it to exit in the test1 function and thus only print "1"

"
#!/usr/bin/ksh

function test1
{
echo "1"
exit 1
}

x=$(test1)
echo "x: $x"
"
I tested this on Linux with zsh running as ksh and on HP-UX 11.11.

Any help much appreciated.

Kris
2 REPLIES 2
Solution

Re: Korn Shell question

Kris,

Well it would never just print "1" as the command substitution you are using is assigning that value to x rather than echoing it to the terminal.

from the man page for ksh :

Command substitution of most special commands (built-ins) that do not
perform I/O redirection are carried out without creating a separate
process. However, command substitution of a function creates a
separate process to run the function and all commands (built-in or
otherwise) in that function.


So when you do command substitution - $()of a function that runs in a seperate process, so the exit call just exits that other process and returns to the main parent shell script process.

Generally I use "return" in functions rather than "exit" and then test the return value from the function to decide what to do...

Obviously this is a "constructed" test - what are you actually trying to acheive here?

HTH

Duncan


I am an HPE Employee
Accept or Kudo
Quark
Valued Contributor

Re: Korn Shell question

Thanks Duncan, you confirmed what I was suspecting.

I just ran into this problem when I was reviewing code from somebody else where the script just continued after an exit 1 in a function that was used in cmd substitution.

I will need to change the logic of the script a bit and like you suggested test for the return code.

Thanks for your help