Transform String into Shell Script array

Asked

Viewed 1,023 times

4

I am trying to make a script to backup my database.

But I would not need to provide the name of the bases when running the script, but save each base in a different file.

My script is like this:

#!/bin/bash

BASES= mysql -u *** -p"***" -B -N -e "SHOW DATABASES"    
IFS='\n ' read -r -a array <<< "$BASES"    
echo $BASES
echo $IFS

In the first line I am listing the bases and saving in the variable BASES. The second line, I tried to break the variable into an array separating by line break but it didn’t work.

The exit of BASES that’s how it is:

base1
base2
base3
.
.
.

How to turn this output into an array?

  • Hi Amanda, see if this helps: http://stackoverflow.com/questions/10130280/split-string-into-array-shellscript, http://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash

  • I had already tried the answer of these links but it did not work. My problem is to know which delimiter to use. Since my exit has no comma or dot or anything like that, I tried using n and it didn’t work.

  • I think this may be so: http://stackoverflow.com/questions/19771965/split-bash-string-by-newline-characters or http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash you have a lot of good answers here

  • Not missing a tick ` (or leave the command inside the expansion $( cmd )) in the variable declaration $BASES? From what I see, $BASES should be empty

1 answer

1

Do it like this:

ARRAY=()

while read line
do
   [[ "$line" != '' ]] && ARRAY+=("$line")
done <<< "$BASES"

To check the array:

for x in "${ARRAY[@]}"
do
   echo "$x"
done

Browser other questions tagged

You are not signed in. Login or sign up in order to post.