我试图解析一些 nginx 配置
λ tree sites-enabled/ sites-available/
sites-enabled/
├── bank.cwrcoding.com.conf
├── calendar.cwrcoding.com.conf
├── cloud.cwrcoding.com.conf
├── cwrcoding.com.conf
├── drive.cwrcoding.com.conf
├── groups.cwrcoding.com.conf
├── mail.cwrcoding.com.conf
├── sites.cwrcoding.com.conf
├── studentenverwaltung.cwrcoding.com.conf
├── wekan.cwrcoding.com.conf
└── www.cwrcoding.com.conf
sites-available/
├── bank.cwrcoding.com.conf
├── calendar.cwrcoding.com.conf
├── cloud.cwrcoding.com.conf
├── cwrcoding.com.conf
├── drive.cwrcoding.com.conf
├── groups.cwrcoding.com.conf
├── mail.cwrcoding.com.conf
├── sites.cwrcoding.com.conf
├── studentenverwaltung.cwrcoding.com.conf
├── wekan.cwrcoding.com.conf
└── www.cwrcoding.com.conf
site-enabled/* 文件每个包含一行:
include sites-availabe/cwrcoding.com.conf;
当尝试迭代 site-enabled/* 文件、剪切这些文件并尝试将其内容作为文件读取时,我遇到了一些奇怪的错误,所以我尝试了一个简约的工作解决方案,并从那里开始工作,但仍然出现以下情况发生:
λ for enabled in sites-enabled/*
> do
> echo "$(cat "$enabled") |"
> echo ==========
> done
include sites-available/bank.cwrcoding.com.conf; |
==========
|clude sites-available/calendar.cwrcoding.com.conf;
==========
|clude sites-available/cloud.cwrcoding.com.conf;
==========
|clude sites-available/cwrcoding.com.conf;
==========
|clude sites-available/drive.cwrcoding.com.conf;
==========
|clude sites-available/groups.cwrcoding.com.conf;
==========
|clude sites-available/mail.cwrcoding.com.conf;
==========
|clude sites-available/sites.cwrcoding.com.conf;
==========
|clude sites-available/studentenverwaltung.cwrcoding.com.conf;
==========
include sites-available/wekan.cwrcoding.com.conf; |
==========
|clude sites-available/www.cwrcoding.com.conf;
==========
正如您所看到的,对于大多数网站来说,猫输出被替换为应该的文本后命令替换。
谁能解释发生了什么?还是我发现了一些错误?
如果您想查看这些文件:https://github.com/cwrau/nginx-config
答案1
问题是您的文件具有 DOS/Windows 风格的行结尾。作为快速解决方法,替换:
echo "$(cat "$enabled") |"
和:
echo "$(tr -d '\r' <"$enabled") |"
这里,tr
在显示文件之前删除回车符,避免了该问题。
然而,如果您的文件打算在 Unix 系统上使用,您最好使用一种dos2unix
或类似的实用程序从文件本身中删除回车符。
例子
让我们创建两个 DOS 风格的文件:
$ echo 'include sites-availabe/cwrcoding.com.conf;' | unix2dos > sites-enabled/file1
$ echo 'include sites-availabe/cwrcoding.com.conf;' | unix2dos > sites-enabled/file2
让我们运行原始命令:
$ for enabled in sites-enabled/*; do echo "$(cat "$enabled") |"; echo ==========; done
|clude sites-availabe/cwrcoding.com.conf;
==========
|clude sites-availabe/cwrcoding.com.conf;
==========
注意损坏的输出。
应用后tr
,我们会收到预期的输出:
$ for enabled in sites-enabled/*; do echo "$(tr -d '\r' <"$enabled") |"; echo ==========; done
include sites-availabe/cwrcoding.com.conf; |
==========
include sites-availabe/cwrcoding.com.conf; |
==========