Alexandre Silva
Alexandre Silva

Reputation: 13

Shell Script - Force output to the the command line inside a function

Im modifying a shell script that is responsible of an installation. The script has several functions, and all the output must be redirected to a log file. However, in the beginning of every function, I have to print in the terminal something like "Starting function ". What happens is that, when I call a function inside a code block, because I'm redirecting the output of that code block to a log file, everything is redirected, even the first information that I want to show in the terminal.

Example of a function:

function_xpto() {
        echo -n "starting function ...."

        if  (   {
                    command1 && command2 && ... && commandN;
                } >> $LOG_FILE 2>&1
            );
        then
            echo "SUCCESS"
        else
            echo "FAILED"
            exit 1
        fi;
}

Example of a call to the function:

        echo -n "running script"

        if  (   {
                    command1 && function_xpto;
                } >> $LOG_FILE 2>&1
            );
        then
            echo "SUCCESS"
        else
            echo "FAILED"
            exit 1
        fi;

When I call the function inside the code block, everything (and I understand why) is redirected.

So, I want a way to force a command (eg: echo) to be sent to the terminal, or at least, to don't be sent to the log file.

Thanks in advance.

Upvotes: 1

Views: 2049

Answers (2)

Ipor Sircer
Ipor Sircer

Reputation: 3141

 echo -n "running script" > /proc/$PPID/fd/1

Example for @chepner:

$ cat subshell.sh
#!/bin/bash
write () { echo noppid
echo echowithppid > /proc/$PPID/fd/1
}
write >/dev/null 2>&1
$ ./subshell.sh
echowithppid
$ 

Upvotes: 0

chepner
chepner

Reputation: 531075

/dev/tty is the controlling terminal for a process, if it has one.

function_xpto() {
        echo -n "starting function ...." > /dev/tty

        if  (   {
                    command1 && command2 && ... && commandN;
                } >> $LOG_FILE 2>&1
            );
        then
            echo "SUCCESS"
        else
            echo "FAILED"
            exit 1
        fi;
}

Upvotes: 1

Related Questions