0

I'm trying to use the output of a bash command as an input variable for a sql-query:

#!/bin/bash

mysql --user=root --password=root database << QUERY_INPUT

#Get temp from sensor.
current_temp=$(sed -n 2,2p /sys/bus/w1/devices/xxx/w1_slave | awk '{print $10}' | awk -F= '{print $2}')

#SQL query
INSERT INTO temperatures (tdate, ttime, temperature)
VALUES (CURRENT_DATE,CURRENT_TIMESTAMP,'$current_temp')
QUERY_INPUT

Im getting:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'current_temp=24750

INSERT INTO temperatures (tdate, ttime, temperature)
VALUES' at line 1"

How can I pass only the numbers to the query?

2
  • What are you trying to extract from /sys/bus/w1/devices/xxx/w1_slave? That line looks like it could be simplified greatly Commented Aug 14, 2014 at 18:24
  • xxx is just a serial number for a DS18B20 temperature sensor. Commented Aug 14, 2014 at 18:48

3 Answers 3

2

The command that sets current_temp is not part of the SQL output. Move it outside the here document.

Only code meant to be passed to mysql can appear in the here document, which means you need to move the command that sets current_temp, and all shell comments, outside the here document.

#!/bin/bash

#Get temp from sensor.
current_temp=$(sed -n 2,2p /sys/bus/w1/devices/xxx/w1_slave | awk '{print $10}' | awk -F= '{print $2}')

mysql --user=root --password=root database << QUERY_INPUT
INSERT INTO temperatures (tdate, ttime, temperature)
VALUES (CURRENT_DATE,CURRENT_TIMESTAMP,'$current_temp')
QUERY_INPUT

As mentioned in the comments, there are several ways to simplify setting current_temp. A sample:

  1. Use a single awk command:

    current_temp=$( awk 'NR==2 {print $10}' /sys/bus/w1/devices/xxx/w1_slave )
    
  2. Use pure bash:

     { read; read -a fields; current_temp=${fields[9]}; } < /sys/bus/w1/devices/xxx/w1_slave
    
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

#!/bin/bash
current_temp=$(sed -n 2,2p /sys/bus/w1/devices/xxx/w1_slave | awk '{print $10}' | awk -F= '{print $2}')
mysql --user=root --password=root database -e "INSERT INTO temperatures (tdate, ttime, temperature) VALUES (CURRENT_DATE,CURRENT_TIMESTAMP,$current_temp)"

I can unfortunately not test it at the moment

1 Comment

Thank you (and the other guys answering), that worked perfect!
0

Try this:

INSERT INTO temperatures (tdate, ttime, temperature)
VALUES (CURRENT_DATE,CURRENT_TIMESTAMP,'"$current_temp"')
QUERY_INPUT

Quoting "$current_temp" within single quote should pass the string as a quoted string, which is valid for SQL.

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.