1

I like to write a script or a function (not sure which one yet) that will be called by another script. The script or function is to generate several values. How can I write these in bash so that in the other script I can get the values returned by the script or function?

Examples are specially appreciated!

Thanks and regards!

3 Answers 3

5

Use the Bash variable $IFS (internal field separator)

dfunc () {echo "first base:second base:third base:home"}

saveIFS=$IFS
IFS=":"
dval=($(dfunc))    # make an array
IFS=$saveIFS       # put $IFS back as soon as you can, you'll thank me
echo ${dval[1]}

Outputs:

second base

If you use a character that won't appear in your data, for example a colon, then you can use other characters, such as spaces.

And don't use backticks, use $().

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

Comments

1

Have the script generating the output send its output to stdout, and have the calling script pull it in with backticks. Example code:

script1.sh:

#!/bin/bash
echo 1 2 3 4

script2.sh:

#!/bin/bash

for ITEM in `script1.sh`
do
    echo Item = $ITEM
done

2 Comments

Back ticks are a horrible idea.
Wow, that's harsh. There's a reason there are two different sets of syntax - sometimes one is more convenient. Not to mention that some shells (admittedly old and busted ones) don't do $() anyway.
0

As a string delimited by a well-known character (e.g., the colon, as is the convention for $PATH and the like)?

3 Comments

After that how do you extract those values? Do you mean function or script? Could you give some examples?
You can just send them to STDOUT, and capture that with your program, or you can pipe them to a file, and then read the file. If you're using perl you can just do something like: $output = myScript.sh; Good old perl.
There are supposed to be backticks "`" around the myScript.sh bit.

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.