如何有条件地将命令输出重定向到/dev/null?

编程入门 行业动态 更新时间:2024-10-24 06:24:38
本文介绍了如何有条件地将命令输出重定向到/dev/null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个剧本.我想给这个脚本一个安静的模式和一个冗长的模式.

I have a script. I would like to give this script a quiet mode and a verbose mode.

这等效于:

if $verbose then redirect="> /dev/null" fi echo "Verbose mode enabled" $redirect # This doesn't work because the redirect isn't evaluated.

与为每个受影响的语句编写if-elses相比,我真的希望有一种更好的方法.

I'd really like a better way of doing this than writing if-elses for every statement affected.

eval可以工作,但是对其他变量有明显的副作用.

eval could work, but has obvious side effects on other variables.

推荐答案

您可以编写包装函数:

redirect_cmd() { # write your test however you want; this just tests if SILENT is non-empty if [ -n "$SILENT" ]; then "$@" > /dev/null else "$@" fi }

然后您可以使用它来通过重定向运行任何命令:

You can then use it to run any command with the redirect:

redirect_cmd echo "unsilenced echo" redirect_cmd ls -d foo* SILENCE=1 redirect_cmd echo "nothing will be printed" redirect_cmd touch but_the_command_is_still_run

(如果您需要做的就是对此回显,那么您当然可以使函数更简单,只需回显第一个参数,而不是将它们全部作为命令运行)

(If all you need to do is echo with this, you can of course make the function simpler, just echoing the first argument instead of running them all as a command)

更多推荐

如何有条件地将命令输出重定向到/dev/null?

本文发布于:2023-07-06 07:33:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047332.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   重定向   命令   null   dev

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!