简体   繁体   中英

User Input to mysql statement

I have a bash script that I'd like to use to pull an IP address from a database. I can't seem to get the $1 to populate.

The command is: ./goto.sh 2010.

I want it to take 2010 and search the database for it.

goto.sh:

#!/bin/bash
ip=`mysql -Ns wksips -e 'SELECT IP FROM ips WHERE ID LIKE '%'''$1''';`

echo $ip

I have the % sign because all units begin with wks, for example wks2010.

I've tried changing the quotes around but it still fails when run in mysql.

++ mysql -Ns wksips -e 'SELECT IP FROM ips WHERE ID LIKE %$1' ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%$1' at line 1

Appreciate any help.

I would write it this way:

ip=$(mysql -Ns wksips -e "SELECT IP FROM ips WHERE ID LIKE '%$1'")

Use double-quotes at the shell argument level, which allows variables like $1 to be expanded inside the double-quoted string.

Then use single-quotes only for delimiting the string literal in the SQL syntax.

I prefer $(...) instead of back-ticks for command substitution in shell. Using $(...) is great because if the command itself needs some command substitution, you can keep nesting those structures as much as you want. Doing the same thing with back-ticks requires backslashes, and that gets to be maddening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM