In the following very simple ksh script example, I need to ask if func1 results equal to 4 ,
This is what I did in the example but this script does not print the “function result = 4” as I expected it to.
What do I need to change in the [[……]] in order to print the “function result = 4”
Remark – func1 must be in the [[…..]]
#!/bin/ksh
func1()
{
return 4
}
[[ ` func1 ` = ` echo $? ` ]] && print "function result = 4"
You need
OR
There are several issues in the code that you present, so let me try to explain (You’re making it more complicated than it need be).
No. 1 is your use of back-ticks for command substitution, these have been deprecated in the ksh language since ~ 1995! Use $( … cmd ) for modern cmd-substitution. We often see backticks listed as a nod to portability, but only scripts written for systems where the Bourne shell is the only shell available require the use of backticks. (well, I don’t know about dash or ash, so maybe those too).
No 2. is that $? gets set after ever function or command or pipeline is executed and is the return code of that last command. It is a value between 0-255. When you have code like
cmd ; rc=$? ; echo $?; you’re now echoing the status of the assignment ofrc=$?(which will almost always be 0), AND that is why you will see experienced scriptors save the value of $? before doing anything else with it.Recall that command-substitution uses what ever is the output of the
$( ... cmd ...)or backtics enclosed command whilereturnsets the value of$?(until the very next command execution resets that value).I hope this helps.