正确的MySQL用户名/密码,但从脚本运行时得到访问被拒绝错误

我目前正在尝试从一个shell脚本中运行以下命令。

/usr/bin/mysql -u username -ppassword -h localhost database 

它在手动执行时非常好,而不是在脚本中执行。 当我尝试执行包含该命令的脚本时,出现以下错误:

 ERROR 1045 (28000) at line 3: Access denied for user 'username'@'localhost' (using password: YES) 

我从字面上将工作命令复制并粘贴到脚本中。 为什么错误? 作为一个旁注:最终的目的是用cron运行脚本。

编辑:这是我尝试运行的脚本的精简版本。 你可以忽略大部分,直到它连接到第19行的MySQL。

 #!/bin/sh #Run download script to download product data cd /home/dir/Scripts/Linux /bin/sh script1.sh #Run import script to import product data to MySQL cd /home/dir/Mysql /bin/sh script2.sh #Download inventory stats spreadsheet and rename it cd /home/dir /usr/bin/wget http://www.url.com/file1.txt mv file1.txt sheet1.csv #Remove existing export spreadsheet rm /tmp/sheet2.csv #Run MySQL queries in "here document" format /usr/bin/mysql -u username -ppassword -h localhost database << EOF --Drop old inventory stats table truncate table table_name1; --Load new inventory stats into table Load data local infile '/home/dir/sheet1.csv' into table table_name1 fields terminated by ',' optionally enclosed by '"' lines terminated by '\r\n'; --MySQL queries to combine product data and inventory stats here --Export combined data in spreadsheet format group by p.value into outfile '/tmp/sheet2.csv' fields terminated by ',' optionally enclosed by '"' lines terminated by '\r\n'; EOF 

编辑2:经过一些更多的testing,问题是在命令的末尾的<< EOF 。 这里是“这里的文件”。 当被移除时,该命令正常工作。 问题是,我需要<< EOF ,以便MySQL查询将运行。

事实certificate,根本原因是我试图执行没有适当的权限的MySQL查询中的命令。 这就是为什么它说at line 3行错误,意思是sql查询的第3行。 我切换到root ,现在一切正常。 这个问题更清楚的问及答案:

MySQL访问拒绝与“这里文件”

你在本地主机上使用相同的命令/脚本? 或者远程服务器,记住mysql.users中的每个条目都是由host设置的,所以如果你只做了本地主机,它将不能用于远程访问,反之亦然。

如果它是一个bash shell脚本,你可以设置#! 行到#!/bin/bash -x ,这使脚本输出到控制台正在执行的确切命令。 然后,您可以采取该命令并手动尝试,或者看看它可能与您已经手动运行的不同。

如果不这样做,那么从脚本中运行这个命令的地方发布一段代码会有帮助,所以我们有更多的上下文来回答这个问题。

最后一行仅包含“EOF \ n”是绝对有意义的。 行尾的单个空格符号可以使标记与第一行中使用的标记不同。 在你的情况下,只需在“EOF”行之后添加空string。

将注释行添加到最后一行代码是一种好习惯。

 /usr/bin/mysql -u username -ppassword -h localhost database << EOF . . . . . EOF ###