0

I want to call a script from inside a script like below

weeknum=$(getweek )

Here getweek is a script file. How to write the sub script file so that it returns the value to weeknum. Should i use return or exit with status as return value

1

You can very well use echo for that purpose.

$ cat new
echo 1
$ number=$(./new)
$ echo $number
1

I think that serves the purpose. Also note that new above is the script that you're gonna write.

comment below if I mis-assumed something

1

The $(cmd) syntax captures the standard output of cmd (stripped of trailing newline characters).

So all you have to do is have getweek output the information:

#! /bin/sh -
date +%V # or %U or %W

date outputs the week number on its stdout which it inherits from sh, which in the case of weeknum=$(getweek) is set to a pipe or socketpair by the shell at the other end of which the shell reads that output to store in the weeknum variable.

You could also return the week number in the exit status:

#! /bin/sh -
exit "$(date +%W)"

Which you obtain with:

getweek
weeknum=$?

but I would advise against that. The exit status should be reserved for error reporting or limited to true/false values.

Typically above, if there's an error (in forking a process, in executing date or sh) or the process is killed, you'll get a non-zero exit status which should not be treated as a week number.

0

You can try the below one

output=$(sh <scriptname>)

And I feel in this case you can also try writing a function with in your script which should help to achieve your goal.

0

Put value to the stdout using any command and read it.

# somesubscript
# do something
echo "my value is here"   # echo is a method to put something to the stdout

Give execute priv. for subscript:

chmod a+rx somesubscript

And use it

val=$(./somesubscript)
echo "$val" # will echo my value is here

return and exit is used to tell caller was it okay or not. Not for return values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.