Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使linux脚本从脚本中输出到新的文本文件?_Linux_Bash_Shell_Scripting - Fatal编程技术网

如何使linux脚本从脚本中输出到新的文本文件?

如何使linux脚本从脚本中输出到新的文本文件?,linux,bash,shell,scripting,Linux,Bash,Shell,Scripting,我在Linux中编写了一个脚本getInfo.sh,它收集有关用户、日期、登录到当前环境的用户数量以及许多其他功能的信息 我可以很容易地在文件外找到它所在的位置/getInfo.sh>results.txt 但是,我希望这在脚本中自动发生 如果我将/getInfo.sh>results.txt包含在脚本本身中,它将创建一个无限循环,因为每次它点击/getInfo.sh时,它将重新运行脚本并创建一个无限循环 这里有其他选项吗?如果您想输出包括错误在内的所有内容,请将此作为脚本中的第一个命令: ex

我在Linux中编写了一个脚本
getInfo.sh
,它收集有关用户、日期、登录到当前环境的用户数量以及许多其他功能的信息

我可以很容易地在文件外找到它所在的位置
/getInfo.sh>results.txt

但是,我希望这在脚本中自动发生

如果我将
/getInfo.sh>results.txt
包含在脚本本身中,它将创建一个无限循环,因为每次它点击
/getInfo.sh
时,它将重新运行脚本并创建一个无限循环


这里有其他选项吗?

如果您想输出包括错误在内的所有内容,请将此作为脚本中的第一个命令:

exec 2>&1>& results.txt
exec 1>& results.txt
exec > >(tee -ia results.txt)
exec 2> >(tee -ia errors.txt)
如果不希望错误出现在文件中,而是希望将其输出到控制台,则将其作为脚本中的第一个命令添加:

exec 2>&1>& results.txt
exec 1>& results.txt
exec > >(tee -ia results.txt)
exec 2> >(tee -ia errors.txt)

一些额外的

如果希望将所有内容不包括错误输出到文件并显示在控制台中,则将其作为脚本中的第一个命令添加:

exec 2>&1>& results.txt
exec 1>& results.txt
exec > >(tee -ia results.txt)
exec 2> >(tee -ia errors.txt)
如果还希望将错误输出到文件并显示在控制台中,请将上面显示的命令和此命令添加到脚本的开头:

exec 2>&1>& results.txt
exec 1>& results.txt
exec > >(tee -ia results.txt)
exec 2> >(tee -ia errors.txt)

第一个解决方案的信贷


第二个解决方案的功劳是:

添加
exec 2>&1>results.txt&
作为脚本中的第一个命令。或者,只需将脚本的每个输出重定向到新文件,例如
echo“something important”>>新建文件
-如果没有提供参数,您可以将输出文件作为参数传递或写入默认名称。更正我以前的评论:将
exec 2>&1>&results.txt作为脚本中的第一个命令添加。这将把所有输出(包括错误)重定向到
results.txt
。如果您希望错误消息仍然打印到控制台,请改用此
exec 1>&results.txt