printf


Convert a list of integers from MySQL to a Bash array

The following code will connect to a MySQL server, it will get a list of integers and convert the results to a bash array that will be iterated using a for loop and they will be printed using zero padding.


IDS_RAW=$(mysql --user="myuser" --password="mypass" --host="db.example.com" --database="mydb" --batch --compress --skip-column-names --execute="
  SELECT
    Id
  FROM
    Users
  WHERE
    Status = 0;
");

OLDIFS=$IFS;
IFS=$'\n' command eval;
'IDS=($IDS_RAW)';
IFS=$OLDIFS;

echo "Will process the following user IDs '${IDS[@]}'";

for ID in "${IDS[@]}"; do
  LEADING_ZERO=$(printf %08d $ID);
  echo "ID $LEADING_ZERO";
done;