Bash

為什麼bash之後用文本替換命令替換中的文本

  • January 9, 2018

我試圖解析一些 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

sites-enabled/* 文件每個都包含一行:

include sites-availabe/cwrcoding.com.conf;

當嘗試遍歷啟用站點的/ *文件,剪切這些文件並嘗試將其內容作為文件讀取時,我遇到了一些奇怪的錯誤,所以我嘗試了一個簡約的工作解決方案,並從那裡開始工作,但是以下發生:

λ 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;
==========

如您所見,對於大多數站點,cat輸出的第一個字元被替換為命令替換後的文本。

誰能解釋發生了什麼?還是我發現了一些錯誤?

如果您想查看文件:https ://github.com/cwrau/nginx-config

問題是您的文件具有 DOS/Windows 樣式的行尾。作為一種快速解決方法,請替換:

echo "$(cat "$enabled") |"

和:

echo "$(tr -d '\r' <"$enabled") |"

在這裡,tr在顯示文件之前刪除輸入符,避免出現問題。

dos2unix但是,如果您的文件打算在 Unix 系統上使用,則最好使用一個或類似的實用程序從文件本身中刪除輸入符。

例子

讓我們創建兩個 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; |
==========

引用自:https://unix.stackexchange.com/questions/415651