shell 变量赋值带有颜色属性时,使用find命令时无法正常引用

shell 变量赋值带有颜色属性时,使用find命令时无法正常引用。且使用033[0m 无法去除颜色属性。

[root@localhost tmp]# soft=Install_Nginx
[root@localhost tmp]# soft=${soft#*_}
[root@localhost tmp]# find / ! -path "$HOME/*" -type f -iname $soft |xargs file {} |grep "\<ELF\>"
/usr/local/nginx/sbin/nginx: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=b107cade828d698c9aa6b15a2fe1834e989e150a, not stripped
# 当变量带有颜色属性时无法找到
[root@localhost tmp]# soft=$(echo -e "\033[32mInstall_Nginx\033[0m")
[root@localhost tmp]# soft=${soft#*_}
[root@localhost tmp]# find / ! -path "$HOME/*" -type f -iname $soft |xargs file {} |grep "\<ELF\>"

使用如下方法去除属性无效:

[root@localhost tmp]# A=$(echo -e "\033[0m${soft}\033[0m")
[root@localhost tmp]# echo $A
Install_Nginx #还是带有颜色输出

使用字符串截取后颜色消失,但使用find依旧找不此文件

[root@localhost tmp]# soft=$(echo -e "\033[32mInstall_Nginx\033[0m")
[root@localhost tmp]# echo $soft
Install_Nginx
[root@localhost tmp]# soft=${soft#*_}
[root@localhost tmp]# echo $soft
Nginx
[root@localhost tmp]# find / ! -path "$HOME/*" -type f -iname $soft |xargs file {} |grep "\<ELF\>"
[root@localhost tmp]# 
还望大佬们帮忙解答一下
阅读 3.7k
2 个回答

所谓颜色属性,其实就是一些特殊字符。所以加颜色属性,相当于在串上附加了额外的字符,当然就就找不到了。

比如你想找 Install_Nginx ,实际查的缺是 %Install_Ning@ ,那当然找不到(颜色字符并不是% @ ,为了看着方便随便写的)

然后说 ${soft#*_} 。这个在 shell 里是去除前缀的,带颜色字符的,处理之后其实变成了 Nginx@ 。前面那个去掉了,后面那个还在,虽然 echo 出来看不到。所以依然找不到。

其实题主目的就是去除颜色字符串中的颜色转移字符呗,看我下面的实验过程:

[calvin calvin/test] -> soft=$(echo -e "\033[32mInstall_Nginx\033[0m")
[calvin calvin/test] -> echo $soft 
Install_Nginx
[calvin calvin/test] -> echo ${soft#*m}
Install_Nginx
[calvin calvin/test] -> touch ${soft#*m}
[calvin calvin/test] -> ls
Install_Nginx?[0m
[calvin calvin/test] -> touch ${soft%\033*}
[calvin calvin/test] -> ls
?[32mInstall_Nginx?[0m
[calvin calvin/test] -> touch ${soft%$(echo -e "\033")*}
[calvin calvin/test] -> ls
?[32mInstall_Nginx

结论:

  1. 字符串本身包含有转义序列,\033是个八进制数,用来做颜色转义(类似C语言的)。转移序列被echo解释为颜色,但是字符串本身仍然有前缀和后缀,touch时就看出来了。
  2. 去除前缀和后缀的转义序列,直接在命令行上输入八进制数\033不行,借用了echo的输出。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题