If inner.sh is
#...
echo first
echo second
echo third
And outer.sh is
var=`./inner.sh`
# only wants to use "first"...
How can var be split by whitespace?
Try this:
var=($(./inner.sh))
# And then test the array with:
echo ${var[0]}
echo ${var[1]}
echo ${var[2]}
Output:
first
second
third
Explanation:
var=(first second third), for example.$(./inner.sh) runs the inner.sh script, which prints out first, second, and third on separate lines. Since we don't didn't put double quotes around $(...), they get lumped onto the same line, but separated by spaces, so you end up with what it looks like in the previous bullet point.var=( $( echo "1 2 3" ; echo "4 5 6" ) ) ; echo ${var[0]} I expected "1 2 3", it yields "1". Depends on your use case. mapfile does what I need.var=( ... command with IFS=$'\n' and in the next line unset the internal field separator of bash with unset IFS.Don't forget the builtin mapfile. It's definitely the most efficient in your case: If you want to slurp the whole file in an array, the fields of which will be the lines output by ./inner.sh, do
mapfile -t array < <(./inner.sh)
Then you'll have the first row in ${array[0]}, etc...
For more info on this builtin and all the possible options:
help mapfile
If you just need the first line in a variable called firstline, do
read -r firstline < <(./inner.sh)
These are definitely the most efficient ways!
This small benchmark will prove it:
$ time mapfile -t array < <(for i in {0..100000}; do echo "fdjsakfjds$i"; done)
real 0m1.514s
user 0m1.492s
sys 0m0.560s
$ time array=( $(for i in {0..100000}; do echo "fdjsakfjds$i"; done) )
real 0m2.045s
user 0m1.844s
sys 0m0.308s
If you only want the first word (with space delimiter) of the first line output by ./inner.sh, the most efficient way is
read firstword _ < <(./inner.sh)
brew info mapfile || echo "found $(brew desc -s mapfile | wc -l) references to mapfile" -> Error: No available formula for mapfile found 0 references to mapfile let me go on... sh-3.2$ mapfile -> sh: mapfile: command not foundmapfile is a Bash≥4 builtin. Not available in POSIX shells or Bash<4. Seems you're running 3.2; you're screwed. Unless you install a more recent version of Bash.mapfile -t var < <( echo "1 2 3" ; echo "4 5 6" ) ; echo ${var[1]} correctly yields 4 5 6.mapfile — just because it's a common source of error on OS X. And I have no idea why your error is prefixed with -bash. Sorry, I don't have OS X available. Moreover, there are lots of people using mapfile on OS X around here, so I suspect that you're the one doing something wrong. I was just trying to help you, starting with the basic, suggesting that you double check the version number. Now I'm sorry I can't be of any further help.You're not splitting on whitespaces but rather on newlines. Give this a whirl:
IFS=$'
'
var=$(./echo.sh)
echo $var | awk '{ print $1 }'
unset IFS
var?newvar = $(echo $var | awk '{ print $1 }') and access $newvar
for word in $var; do?