Majid ff
Majid ff

Reputation: 249

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?

Upvotes: 1

Views: 3114

Answers (2)

APM
APM

Reputation: 76

Is there a reason you are not using function?

function log() {
    echo ${1}
    log -p v -t "ScriptName.sh" ${1}
}

Upvotes: 0

William Pursell
William Pursell

Reputation: 212298

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

Upvotes: 2

Related Questions