Linux云计算交流群:720995729

linux command

很多时候,我们已经知道利用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文件结束符引起来,就可以抑制变量扩展,进而解决此问题。

标签: linux教程, cat命令创建脚本问题

添加新评论