tags:

views:

164

answers:

3

Hi,

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!

A: 

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

scrible
After that how do you extract those values? Do you mean function or script? Could you give some examples?
Tim
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.
Satanicpuppy
There are supposed to be backticks "`" around the myScript.sh bit.
Satanicpuppy
A: 

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
Carl Norum
Back ticks are a horrible idea.
scragar
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.
Carl Norum
+5  A: 

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 $().

Dennis Williamson