Score:0

Mysql in bash script

in flag

Hi Im running the following mysql query using a bash script:

#!/bin/bash

set -f        # disable globbing
IFS=$'\n'     # set field separator to NL (only)

arr=($(sudo mysql -u root -h localhost  -e "USE mydb;SELECT * FROM sites" | awk 'NR>1'))

echo $arr

which is returning the following:

1       Jhon     Richards     [email protected]

Then I'm trying to get just the firstname (Jhon) and store in a variable, I'm adding this line:

firstname=$arr | awk '{print $2}'

However I'm doing something wrong because then I'm trying to print the result with the following line:

echo $firstname

Which is not printing anything. What I'm doing wrong here?

in flag
Silly question, but why not write a better SQL query? If all you need is the vale of `firstname`, then `SELECT firstname FROM sites` would supply this
jpbrain avatar
ca flag
what if you just do "echo ${arr[1]}" ?
Terrance avatar
id flag
Your firstname command is wrong. You would need to have it as an echo instead just like you have in your `echo $firstname` command. It should be `firstname=$(echo $arr | awk '{print $2}')`
Iosef avatar
in flag
matigo: I cant to do that because I need the other columns to be stored in variables as well. jpbrain: I not getting what I need. Terrance: You gave the right answer
Score:0
id flag
firstname=$arr | awk '{print $2}'

is actually trying to set firstname to the command of what $arr is set for so it should error out with command not found.

If you echo $arr as a complete command then you can grab the positional parameter as needed.

firstname=$(echo $arr | awk '{print $2}')

There also are other ways to get positional parameters. Feel free to look them up.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.