e_scape
e_scape

Reputation: 99

How to execute SQL command with parameters in bash script

I would like to make a bash script which will add user to my custom table in MySQL database. I have username as script argument stored in variable $USERNAME and I need to execute this query into MySQL server:

INSERT INTO `user` VALUES ('$USERNAME', password)

I know how to execute a sql file but that won't help me when I have username in variable. The only way I can think of is to execute php file with GET values and execute sql command in php. And I'm not eve sure that with php will work as I think.

Is there any better way?

Thanks

EDIT: After your helpfull answers I went with this command which works:

mysql -ppassword --default-character-set=utf8 -e "INSERT INTO table VALUES (\"$USERNAME@\",\"password\")" database

Upvotes: 1

Views: 4654

Answers (2)

Josh Jolly
Josh Jolly

Reputation: 11786

You could try using a heredoc:

#!/bin/bash

USERNAME="example"

mysql <<MYSQL
INSERT INTO user VALUES ('$USERNAME', password);
MYSQL

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80639

The command would be:

mysql -pyourpasswordwithoutspaces -e "Your insert query goes here with semicolon;"

I'm not sure if the semicolons are necessary or not, but it always good to provide them.

Upvotes: 0

Related Questions