0

I want to get a value form show variables query using the shell script. This is the command i used.

data=$(mysql -u root -proot -t -e "show variables where variable_name = 'datadir';"  -B --skip-column-names)

Out put result is,

+---------------+-----------------+
| Variable_name | Value           |
+---------------+-----------------+
| datadir       | /var/lib/mysql/ |
+---------------+-----------------+

So i just want to get the value.

/var/lib/mysql/

This is the Script which i try,

data=$(mysql -u root -proot -t -e "show variables where variable_name = 'datadir';"  -B --skip-column-names)
data2=$(echo $data | tr "+---------+-----------------+" "\n")
data3=$(echo $data2 | tr "|" "\n")
data4=$(echo $data3 | tr "datadir " "\n")
echo $data4 

its returning "/v /l b/mysql/".

3
  • 2
    Instead of fiddling with shell to get rid of the borders, I'd rather make MySQL not print them in the first place. Commented May 19, 2020 at 15:26
  • 1
    Get rid of the -t option. It's overriding -B, so you get the borders. Commented May 19, 2020 at 15:34
  • Thanks border removed. But how to get the remove "datadir" from the result. Commented May 19, 2020 at 15:47

1 Answer 1

1

First, don't use the -t and -B options together (in addition, prefer --batch over -B, as -B is deprecated (see Get the sql query result without the table format).

Next, tr is intended to replace single characters only. If you want to replace more characters, you could use sed or just Bash. If you want the second word in a string of characters, you could use cut.

Pure Bash

data=$(mysql -u root -proot -e "show variables where variable_name = 'datadir';"  --batch --skip-column-names)
echo "${data//datadir/}"

sed

data=$(mysql -u root -proot -e "show variables where variable_name = 'datadir';"  --batch --skip-column-names)
sed 's/datadir//g' <<< "$data"

cut

data=$(mysql -u root -proot -e "show variables where variable_name = 'datadir';"  --batch --skip-column-names)
cut -d' ' -f2 <<< "$data"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.