$'\r' - 在 bash 中找不到命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26068769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:25:20  来源:igfitidea点击:

$'\r' - command not found in bash

bashshell

提问by LEM01

I have the below script:

我有以下脚本:

#!/bin/sh

#parameters definition
ROOT_PATH=/var/www/
msql_psw="cc"
mysql_login="bb"
mysql_db_name="aa"

echo START MYSQL DUMP

NOW=$(date +"%Y-%m-%d")
SQLFILE="log-$NOW.sql"
mysqldump --add-drop-table -u "$mysql_login" --password="$mysql_psw" "$mysql_db_name" > "$ROOT_PATH/$SQLFILE"

When it's run with sh -x, it gives command not found errors for empty lines, and even non-empty lines don't work correctly:

当它与 一起运行时sh -x,它会为空行提供 command not found 错误,甚至非空行也无法正常工作:

sh -x export_db.sh 
+ $'\r'
: command not found2: 
+ ROOT_PATH=$'/var/www/\r'
+ msql_psw=$'cc\r'
+ mysql_login=$'bb\r'
+ mysql_db_name=$'aa\r'
+ $'\r'
: command not found8: 
+ echo START MYSQL $'DUMP\r'
START MYSQL DUMP
+ $'\r'
: command not found10: 
++ date +%Y-%m-%d
+ NOW=$'2014-10-02\r'
+ SQLFILE=$'log-2014-10-02\r.sql\r'
+ mysqldump --add-drop-table -u $'bb\r' --password= $'aa\r'
: No such file or directory/www/

回答by Charles Duffy

$'\ris the shells way of writing a CR character -- a carriage return. DOS-formatted text files end with CRLF -- in shell parlance, $'\r\n', whereas UNIX text files end with only $\n. Thus, when a DOS-formatted text file is read by UNIX, each line appears to have an extra $\ron the end.

$'\r是 shell 编写 CR 字符的方式——回车。DOS 格式的文本文件以 CRLF 结尾——用 shell 的说法是$'\r\n', 而 UNIX 文本文件只以 $ 结尾\n。因此,当 UNIX 读取 DOS 格式的文本文件时,每一行\r的末尾似乎都有一个额外的 $ 。



Beyond that, some notes (in places, relevant only to prior versions of the question):

除此之外,还有一些注释(在某些地方,仅与问题的先前版本相关):

Expansion operators aren't used in assignments, so

扩展运算符不用于赋值,所以

$ROOT_PATH=/var/www/

needs to be

需要是

ROOT_PATH=/var/www

Beyond that -- use quotes on all expansions. That is:

除此之外 - 在所有扩展上使用引号。那是:

mysqldump \
  --add-drop-table \
  -u "$mysql_login" \
  --password="$mysql_psw" \
  "$mysql_db_name" \
  >"$ROOT_PATH/$SQLFILE"

Otherwise, variables will be split by IFS, glob-expanded, etc.

否则,变量将被 IFS、glob-expanded 等分割。

Finally -- when making such a bold claim as that variables aren't being substituted, try proving it by using set -xin your script (or starting it with #!/bin/sh -x, or running it manually with sh -x yourscript) to log the commands the shell runs as they're actually invoked post-expansion.

最后-制作这样一个大胆的要求时,作为变量没有被取代,试图通过使用证明它set -x在脚本(或启动它#!/bin/sh -x,或手动运行它sh -x yourscript)登录命令外壳运行,因为他们实际上是扩展后调用。