M-BM-特殊字符问题
如果你想亲手执行前面文章中一些代码示例,比如下面这段shell脚本,你用鼠标复制代码将内容粘贴到(Linux)一个文件中:
#!/bin/bash
myfunc() {
echo 'function arg[0]=' $0
echo 'function arg[1]=' $1
echo 'function arg[2]=' $2
}
echo 'script arg[0]=' $0
echo 'script arg[1]=' $1
echo 'script arg[2]=' $2
type myfunc #使用type命令查看myfunc类型
myfunc func1 func2保存该脚本(设置可执行权限)并执行。
$ ./test_func.sh hi you
script arg[0]= ./test_func.sh
script arg[1]= hi
script arg[2]= you
myfunc is a function
myfunc ()
{
echo 'function arg[0]=' $0;
echo 'function arg[1]=' $1;
echo 'function arg[2]=' $2
}
./test_func.sh: line 4: : command not found
./test_func.sh: line 5: : command not found
./test_func.sh: line 6: : command not found可能你会遇到以上奇怪的错误信息,难道文章中的脚本不对?
仔细查看错误信息,提示脚本第4-6行命令找不到,其内容是函数myfunc里三条echo命令的执行。
echo命令没有问题啊,9-11行echo信息正常打印出来了。
那么问题出在哪里?
对比不同区域的echo使用区别,函数里的echo命令前面有空白。
联想是不是这个空白出问题了。我们知道有许多不可打印字符正常情况下我们是看不见的,文本编辑器会以空白字符显示。
我们可以尝试将前面的空白删除,echo命令从行首开始写起。保存执行,脚本运行成功!!!
这验证了我们的想法,那么到底是什么不可打印的字符?
我们通过cat命令显示不可打印字符。它有以下几个选项可以查看不可见字符:
- -E 显示每行结尾符
$ - -T 显示TAB字符为
^I - -v 除了换行符和TAB外特殊字符使用
^和M-标记符号 - -A 显示所有字符,等同于
-vET
使用-A查看脚本所有字符内容:
$ cat -A test_func.sh
#!/bin/bash$
$
myfunc() {$
M-BM- M-BM- echo 'function arg[0]=' $0$
M-BM- M-BM- echo 'function arg[1]=' $1$
M-BM- M-BM- echo 'function arg[2]=' $2$
}$
$
echo 'script arg[0]=' $0$
echo 'script arg[1]=' $1$
echo 'script arg[2]=' $2$
$
type myfunc #M-dM-=M-?M-gM-^TM-(typeM-eM-^QM-=M-dM-;M-$M-fM-^_M-%M-gM-^\M-^KmyfuncM-gM-1M-;M-eM-^^M-^K$
myfunc func1 func2$可以看到4-6行echo命令前面有M-BM- M-BM-不可打印字符存在。
其含义可查看该链接回答:
TheM-BM-characters are an ASCII representation of byte sequence0xc2 0xa0, which is the UTF8 encoding of unicode characterA0- a non-breaking space character. This character can be inserted in both LibreOffice and Microsoft Word documents using the key sequence Ctrl+Shift+SPACE.
本人从Obsidian markdown文本中复制shell代码片段,其文本编码是UTF-8。
$ file shell函数语法.md
shell\345\207\275\346\225\260\350\257\255\346\263: Unicode text, UTF-8 text小结
另外一个常遇到的问题是Windows与Linux换行符不同导致的^M问题。
在执行复制粘贴别人的程序时遇到一些莫名其妙的报错信息时,可以联想是否是因为不同系统/格式编码导致程序文本中出现特殊字符导致的,通过cat命令或者vim特殊字符显示设置验证。
参考资料
https://linux.cn/article-2137-1.html
https://askubuntu.com/questions/357248/how-to-remove-special-m-bm-character-with-sed
Appreciating the dedication you put into your site and
detailed information you offer. It's great to come across
a blog every once in a whle that isn't the sam
out of dare rehashed material. Wonderful read!
I've saved your sitre and I'm adding your RSS feeds to my Google
account.
Hello, just wanted to say, I liked this post. It was
practical. Keep on posting!