根据变量状态

时间:2020-02-07 03:49:04

标签: bash stdout io-redirection stderr

bash脚本中有很多命令,其中有>/dev/null 2>&1用于将stdout和stderr重定向到/ dev / null。

让我们说我有一个名为echoOn的变量,可以为0或1。

如果echoOn等于0,那么我希望保留脚本中命令的重定向。如果它等于1,那么我就不需要重定向,因此命令可以输出。

我不想抑制所有命令的输出,而只禁止脚本中的特定命令。

我是否可以通过一种更抽象的方式来执行此操作,而无需在每个有问题的命令中手动添加if语句?

我对可以传递命令及其参数并将每个命令替换为对上述函数和要执行的命令的调用感到满意。

2 个答案:

答案 0 :(得分:3)

我不确定我是否正确理解了您的要求,但是如何:

# put the lines below at the beginning of the script
if (( echoOn == 0 )); then
    exec 3>/dev/null 2>&3
else
    exec 3>&1
fi

# then execute your commands
echo foo >&3    # a command which wants to switch the redirection
echo warn >&2   # simulates an error
echo bar        # a command which does not need the switch

如果将echoOn设置为0,则终端上仅显示bar

问题是您需要修改代码,将所有>/dev/null 2>&1表达式替换为>&3

[更新]

要同时控制特定命令上的stdout和stderr,请尝试以下操作:

echoOn=0        # set to "1" to ebable stdout/stderr else set to "0"
if (( echoOn == 0 )); then
    exec 3>/dev/null
    exec 4>/dev/null
else
    exec 3>&1
    exec 4>&2
fi

echo foo 1>&3 2>&4          # a command which wants to switch the redirection
(echo warn >&2) 1>&3 2>&4   # simulates an error
echo bar                    # a command which does not need the switch
(echo error >&2)            # simulates anerror

请在要控制其输出的命令中放置1>&3 2>&4

答案 1 :(得分:1)

尝试一下:

.then((jsonData)=>{
    console.log(jsonData);
    var jsonString = JSON.stringify(jsonData);
    var foods = JSON.parse(jsonString)
    for(var item in foods.common) {
        const uri2 = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
        let appid = new Headers();
        appid.append("x-app-id", "19421259")
        let appkey = new Headers();
        appid.append("x-app-key", "54a4e6668518084478d9025d8a5e32a2")
        appid.append('Content-Type', 'application/json')
        let req2 = new Request (uri2, {
            method: 'POST',
            headers: appid,
            body: 
        });

bash脚本中有很多命令,这些命令具有> / dev / null 2>&1,用于将stdout和stderr重定向到/ dev / null。

accepted answer不使用if [ $# -ge 1 -a $1 -eq 0 ]; then exec 3>/dev/null 1>&3 2>&3 else exec 3>&1 fi foo="hello" warn="world" bar="stackoverflow" # then execute your commands echo $foo >&3 # a command which wants to switch the redirection echo $warn >&2 # simulates an error echo $bar # a command which does not need the switch 来获取变量的值。我认为如果您尝试运行脚本,可能会出错。而且您需要同时重定向stdout和stderr。因此,如果您将参数$传递给脚本,那么我的脚本会将它们都重定向到/dev/null,否则它不会重定向。

如果运行0

,则无输出

输出./example.sh 0

./example 1
相关问题