[英]Adding user through bash in MySQL
這是我第一次嘗試在mysql終端中傳遞bash命令,我正在這樣做:
每次安裝應用程序與數據庫進行交互時, 都會創建一個虛擬用戶 。
但是,我所有的嘗試都失敗了,這是我的代碼行:
new_user(){ mysql -u"$1" -p"$2" -e 'CREATE USER "$3"@"$4" IDENTIFIED BY "$5";
GRANT ALL PRIVILEGES ON "$6".* TO "$3"@"$4";
FLUSH PRIVILEGES;
exit;' &&
echo `new MySQL USER has been created ..
name:"$3" server:"$4" password:"$5" database:"$6"` ; }
但是,它給了我這個錯誤 :
ERROR 1064 (42000) at line 1: 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 '"$4".* TO "$1"@"$2"' at line 1
我曾嘗試使用-e
但顯示不成功。
如何在MySQL中傳遞bash變量?
感謝評論,我已經更新了引號的代碼,但是仍然無法將變量傳遞給mysql終端。
new_user() {
SQL="CREATE USER\"$3\"@\"$4\" IDENTIFIED BY \"$5\"; GRANT ALL PRIVILEGES ON \"$6\".* TO \"$3\"@\"$4\"; FLUSH PRIVILEGES; exit;"
mysql -uroot -p1 -e "$SQL" &&
echo new MySQL USER has been created .. name:\"$3\" server:\"$4\" password:\"$5\" database:\"$6\"
}
您可以避免使用HEREDOC
弄清楚如何對引號進行HEREDOC
。
要進行調試,請嘗試將函數分成兩部分。
gen_user_sql(){
cat <<HEREDOC
CREATE USER '$1'@'$2' IDENTIFIED BY '$3';
GRANT ALL PRIVILEGES ON $4.* TO '$1'@'$2';
FLUSH PRIVILEGES;
HEREDOC
}
new_user(){
sqluser="$1"; shift
sqlpswd="$1"; shift
mysql -u"$sqluser" -p"$sqlpswd" -e "$(gen_user_sql $@)"
echo "new user: $@"
}
# see the query
gen_user_sql user host id db
# actually run it
new_user sqlu sqlp user host id db
有新語法的一些注意事項:
$@
傳入的所有變量。 shift
移除會是什么$1
從$@
。 (在shift
之后, $1
返回調用shift
之前的$2
) $(command)
捕獲的輸出command
,在這種情況下,使用它作為字符串輸入到mysql
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.