很多时候,我们已经知道利用cat命令配合重定向可以创建文件,比如这样:
[root@www.lutixia.cn ~]# cat > file <<EOF
> this is test file
> EOF
[root@www.lutixia.cn ~]# cat file
this is test file
但是,在脚本应用中,有时会遇到一些问题。比如,想在脚本中添加变量时,会出现变量不见了(被扩展了),如下:
[root@www.lutixia.cn ~]# cat > newfile <<EOF
> this is newfile
> my name is $name
> EOF
[root@www.lutixia.cn ~]# cat newfile
this is newfile
my name is
可以看到我们设置的$name
变量不见了,原因是没有对name变量赋值,被扩展为空了。
解决方案如下:
[root@www.lutixia.cn ~]# cat > newfile <<'EOF'
> this is newfile
> my name is $name
> EOF
[root@www.lutixia.cn ~]# cat newfile
this is newfile
my name is $name
我们只需要用单引号把EOF文件结束符引起来,就可以抑制变量扩展,进而解决此问题。
以上就是解决cat命令创建文件,变量丢失的详细教程,后续会发布更多硬核技术文章。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。