如果给出参数则输出到文件的简洁方式,否则输出到标准输出

Sha*_*off 2 io-redirection shell-script

我希望我的脚本输出到标准输出,除非它以文件名作为参数。一个明显的方法是这样的:

if [ -e "$1" ]; then
  command_with_output >$1
else
  command_with_output
fi
Run Code Online (Sandbox Code Playgroud)

它非常丑陋并且有重复,所以我想要一种更简洁的方法来做到这一点。

我尝试了以下方法,但不起作用。

[ -e "$1" ] && outfile=$1 || outfile='&1'
command_with_output >$outfile
Run Code Online (Sandbox Code Playgroud)

编辑:这不会改变答案的相关性,但我在提出问题后意识到这touch "$1" && outfile=$1正是我需要的,而不是[ -e "$1" ] && outfile=$1因为文件可能不存在,我想确保我可以写入或创建它,不仅仅是它的存在。我不会改变问题,因为它会使答案不同步。

Sha*_*off 7

exec 可用于将当前脚本的标准输出重定向到另一个文件。

[ -e "$1" ] && exec > $1
command_with_output
Run Code Online (Sandbox Code Playgroud)