androidlinuxshelllogginglogcat

How to redirect shell script output to Logcat in easy way


I can redirect the output of my script file (ScriptName.sh) to logcat in Android like in following:

#!/system/bin/sh
 echo "Comment 1"
 log -p v -t "ScriptName.sh" "Comment 1"

 echo "Comment 2"
 log -p v -t "ScriptName.sh" "Comment 2"

 echo "Comment 3"
 log -p v -t "ScriptName.sh" "Comment 3"

And then I can logcat by:

logcat | grep "ScriptName.sh" 

As you can see I have to write "log" command for every "echo" command. Is there any way to write the log command at the beginning of the script (or any where) and let all echo's go to logcat without repeating the "log" command?


Solution

  • If log could read stdin directly, it would be easier to tee your output to log and /dev/tty. It looks like log doesn't provide that, but it's easy enough to emulate:

    #!/system/bin/sh
    {
    echo Comment 1
    echo Comment 2
    echo Comment 3
    } | tee /dev/tty | while read line; do 
     log -p v -t "$0" "$line"
    done
    

    There are a lot of variations on that theme. It might be cleaner to write a simple wrapper around log that does that for you, and you might want to execute the wrapper near the top of the script with appropriate redirections and pipes. For example (if using a shell that supports process substitution):

    #!/bin/bash                    
    exec > >(tee /dev/tty | log_wrapper ... )
    

    or, if you don't have process substitution available:

    #!/bin/sh                    
    
    trap 'rm -f $FIFO' 0
    FIFO=$(mktemp)
    < $FIFO tee /dev/tty | log_wrapper ... &
    exec > $FIFO  # Redirect all further output to the log wrapper