bash脚本中的变量未按预期工作

时间:2021-05-09 01:46:58

I have this script:

我有这个脚本:

#!/bin/bash
VAR="eric.sql"
sudo mysqldump -c -u username -p1234 dbname > $VAR

But if i run this script I get this error:

但是,如果我运行此脚本,我会收到此错误:

: Protocol error 3: mysql-export.sh: cannot create eric.sql

But if I don't use the variable, but just this:

但是,如果我不使用变量,只是这样:

#!/bin/bash
VAR="eric.sql"
sudo mysqldump -c -u username -p1234 dbname > eric.sql

... it is working well. What do I wrong?

......它运作良好。我错了什么?

2 个解决方案

#1


The problem was that the script had Windows style line breaks (I used notepad). After I used Nano the write the script it was solved.

问题是该脚本具有Windows样式换行符(我使用了记事本)。在我使用Nano之后编写脚本就解决了。

Thanks for the answers!

谢谢你的回答!

#2


sudo can change $PATH variable, depend on your security policy.

sudo可以更改$ PATH变量,具体取决于您的安全策略。

   -E  The -E (preserve environment) option will override the env_reset
       option in sudoers(5)).  It is only available when either the match-
       ing command has the SETENV tag or the setenv option is set in sudo-
       ers(5).

You could add the full path of the file, or remove sudo in that script. This should also work:

您可以添加文件的完整路径,或删除该脚本中的sudo。这应该也有效:

 sudo PATH="$PATH" mysqldump -c -u username -p1234 dbname > $VAR

#1


The problem was that the script had Windows style line breaks (I used notepad). After I used Nano the write the script it was solved.

问题是该脚本具有Windows样式换行符(我使用了记事本)。在我使用Nano之后编写脚本就解决了。

Thanks for the answers!

谢谢你的回答!

#2


sudo can change $PATH variable, depend on your security policy.

sudo可以更改$ PATH变量,具体取决于您的安全策略。

   -E  The -E (preserve environment) option will override the env_reset
       option in sudoers(5)).  It is only available when either the match-
       ing command has the SETENV tag or the setenv option is set in sudo-
       ers(5).

You could add the full path of the file, or remove sudo in that script. This should also work:

您可以添加文件的完整路径,或删除该脚本中的sudo。这应该也有效:

 sudo PATH="$PATH" mysqldump -c -u username -p1234 dbname > $VAR