以下圖兩個文件html
$ cat a.txt id abc def GHT $ cat b.txt abc 12 hgy def 13 hl 123 14 hl2 GHT 11 hgy3
$ cat t3.sh
#!/bin/bash cat a.txt | while read line ; do echo ${line} grep ${line} b.txt sleep 2 done
###返回結果納悶 竟然沒有匹配上,可咱們肉眼都能看出來能匹配的上linux
$ bash t3.sh abc def GHT
###因而使用 -x 參數 調試一下腳本shell
$ bash -x t3.sh + cat a.txt + read line + echo $'abc\r' abc + grep $'abc\r' b.txt + sleep 2 + read line + echo $'def\r' def + grep $'def\r' b.txt + sleep 2 + read line + echo $'GHT\r' GHT + grep $'GHT\r' b.txt + sleep 2 + read line
###竟然有\r ,難怪找不到,grep 的變量已經變了 grep 'abc' 變成grep 'abc\r'百度瞭解到是換行符問題 源文件a中,明明只有abc,def,GHT ,結尾並無帶上r,咱們用***cat -A filename *命令查看文件中全部不可見的字符 ref:https://zhang.ge/488.html Linux終端:用cat命令查看不可見字符vim
$ cat -A a.txt abc^M$ def^M$ GHT^M$
發現每行多了個^M$ ,緣由何在,主要是windows 中編寫的txt 文件在linux中打開時,格式發生了轉變 實驗對比一下,在Linux中vim 手工編輯一個test.txt ,cat -A 查看一下windows
DELL-PC@DESKTOP-KD5L8P2 MINGW64 ~/Desktop/test $ cat -A test.txt bc$ 11$ 123$ asdf$ mn$
結尾只有一個$,咱們知道linux 中$是一行的結束標識符,而咱們的a.txt 是在windows 中編輯的,結尾^M$ 比Linux中結尾$多了符號^M 因此grep 沒法查到,形成grep沒法查找shell傳過來的變量的假象。bash
###修改腳本服務器
#!/bin/bash cat -A a.txt | while read line ; do id = `echo $line | cut -d"^" -f1` grep $id b.txt sleep 2 done #結果 $ bash -x t1.sh + cat -A a.txt + read line ++ echo 'abc^M$' ++ cut '-d^' -f1 + id=abc + grep abc b.txt abc 12 hgy + sleep 2 + read line ++ echo 'def^M$' ++ cut '-d^' -f1 + id=def + grep def b.txt def 13 hl + sleep 2 + read line ++ echo 'GHT^M$' ++ cut '-d^' -f1 + id=GHT + grep GHT b.txt GHT 11 hgy3 + sleep 2 + read line