bash,如何选择是否通过变量在重定向中追加(根据$append使用>或>>)

bash,如何选择是否通过变量在重定向中追加(根据$append使用>或>>),bash,redirect,Bash,Redirect,我需要在脚本或函数中,将输出定向到日志文件,并根据变量决定是否追加或重写 应该是那种显然不起作用的东西 if [ "$append" = "true" ] ; then direction=">>" ; else direction=">" ; fi echo $message "$direction" $targetFile 而不是使用2个独立命令和if语句的简单答案 稍后编辑,这里有一个假设的重复问题:,然而,我更喜欢Ivan在这里的答案,而不是其他帖子中的答案 if [

我需要在脚本或函数中,将输出定向到日志文件,并根据变量决定是否追加或重写

应该是那种显然不起作用的东西

if [ "$append" = "true" ] ; then direction=">>" ; else direction=">" ; fi
echo $message "$direction" $targetFile
而不是使用2个独立命令和if语句的简单答案

稍后编辑,这里有一个假设的重复问题:,然而,我更喜欢Ivan在这里的答案,而不是其他帖子中的答案

if [ "$append" = "true" ] ; then direction="-a" ; else direction= ; fi
echo $message | tee "$direction" $targetFile
在tee的帮助下

$ tee --help
Usage: tee [OPTION]... [FILE]...
Copy standard input to each FILE, and also to standard output.

  -a, --append              append to the given FILEs, do not overwrite
...
玩一下这个

write_to_file () { tee           $2 $1; }
apend_to_file () { write_to_file $1 -a; }

case "$append" in
    1|[Yy]|[Yy]es|[Tt]|[Tt]rue) direction=apend_to_file;;
    *                         ) direction=write_to_file;;
esac

echo            $direction
echo $message | $direction $targetFile

解决方案1:以所需模式打开专用文件描述符

如果[$append=true];然后 exec 3>>$targetFile 其他的 exec 3>$targetFile fi 使用预配置模式输出到targetFile echo$message>&3 解决方案2:始终附加但有条件地删除覆盖文件内容:

如果[!$append=true];然后 重置目标文件 >$targetFile与覆盖的效果相同 fi echo$message>>$targetFile 简表:

[$append=true]| |>$targetFile echo$message>>$targetFile
这回答了你的问题吗?请注意,要获得OP所需的行为,应添加>/dev/null,否则输出将复制到标准输出。