繁体   English   中英

在文本文件中存储变量的Linux命令是什么

[英]What is the Linux command to store variables in text file

我想将一些变量存储在.txt文件中,但是下面的代码仅保存了最后一个变量。 我如何解决它?

$x1 ="a"
$x2 = "b"
$x3 = "c"

>myfile.txt
echo $x1 >myfile.txt
echo $x2 >myfile.txt
echo $x3 >myfile.txt

>是“创建或替换文件,写入输出”。 您想要>> ,这是“用于添加的打开文件”

echo $x1  >myfile.txt  # create/overwrite file
echo $x2 >>myfile.txt  # append to file
echo $x3 >>myfile.txt  # append to file again
COMMAND_OUTPUT >
      # Redirect stdout to a file.
      # Creates the file if not present, otherwise overwrites it.

COMMAND_OUTPUT >>
      # Redirect stdout to a file.
      # Creates the file if not present, otherwise appends to it.

关于I / O重定向的tldp文档

#writes the variables to the files
x1="a"
x2="b"
x3="c"

echo $x1 >> myfile.txt
echo $x2 >> myfile.txt
echo $x3 >> myfile.txt

最简单的方法(最少学习)是使用>>附加到文件:

>myfile.txt
echo $x1 >>myfile.txt
echo $x2 >>myfile.txt
echo $x3 >>myfile.txt

您可以省略无回声的行,而仅使用>而不是>>来获得相同的效果,但是上面显示的一致性有一些优点。

另一种方法是使用I / O分组运算符{}

{
echo $x1
echo $x2
echo $x3
} > myfile.txt

另一种方法是将execI / O重定向结合使用,从此处开始将所有标准输出发送到文件:

exec >myfile.txt
echo $x1
echo $x2
echo $x3

如果需要将开关标准输出恢复为原始输出,则必须先保留它:

exec 3>&1 >myfile.txt
echo $x1
echo $x2
echo $x3
exec 1&>3 3>&-

3>&1表示法将打开文件描述符3作为文件描述符1(标准输出)的副本。 1>&3表示法将文件描述符1(标准输出)作为文件描述符3(之前创建)的副本打开。 3>&-符号关闭文件描述符3。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM