1

I have some functions in util.sh, I want to call function in util.sh and get the return value. Does anyone know how to do?

util.sh

#!/bin/bash
sayhello()
{
    echo $1 "hello"
}

I try to call the function in terminal using the command as below, but got the output "can not found the command sayhello":

sh /home/adnrew/code/test/util.sh sayhello test

and using the code in my perl as below,

$returnvalue = system("/home/adnrew/code/test/util.sh sayhello test ");

can not work too.

How can I call shell script function in my Perl?

1
  • 1
    For doing it out of a Perl script, see answers to this question Commented Jan 14, 2020 at 6:34

1 Answer 1

2

You could source the shell script into the subprocess by

$returnvalue = system(". /home/adnrew/code/test/util.sh; sayhello test");

The parent process (a bash shell, or a perl system subprocess) creates a child bash process when it tries executing a bash shell. Anything defined in the script are thus limited only to the child process and will not reflect in the parent process itself. Sourcing a script (the 'dot' command or just source), on the other hand, runs the definition in the same bash process.

Sign up to request clarification or add additional context in comments.

2 Comments

yes it's can get the return value , but also return a code '0' , is it can not to return the code '0' ??
@georgetovrea The system returns a 0 when all is well. If the return is non-zero then that number packs some info about what went wrong. So zero is good :) See documentation at the link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.