Execute a command if new line is found in script output - android

I am having huge difficulties writing a simple bash script.
I basically want to monitor a debug log 24/7 and listen for a new line. If there is a new line I want it to execute a command.
logcat | grep com.amazon.firelauncher/.Launcher
When I run this code, I get a live debug window, I want to execute a command (reboot for an example) whenever a new line pops up in that command.
How can this be done? I tried sending the output to a file and monitoring that file for filesize change, but it does not work. I really need assistance!

You should be able to use read for this:
#!/bin/bash
while logcat | grep "com.amazon.firelauncher/.Launcher" | read -r line; do
echo "Text read from logcat"
/path/to/executable
done

This was my final answer, but I would not have concluded it if it was not for the help of Martin Konecny, he did all the heavy lifting.
#!/bin/bash
am monitor | while read -r line; do
if [[ $line == *"firelauncher"* ]]
then
am start com.newlauncher.launcher
fi
done

Related

Execute multiple adb shell command in bash script [duplicate]

I'm writing a simple Bash script that simply the call of HadnBrakeCli for render videos.
I also implemented a simple queue option: the queue file just store the line-command it has to call to start a render.
So I wrote a while-loop to read one line at time, eval $line and repeat untill file ends.
if [[ ${QUEUE_MODE} = 'RUN' ]]; then
QUEUE_LEN=`cat ${CONFIG_DIR}/queue | wc -l`
QUEUE_POS='1'
printf "Queue lenght:\t ${QUEUE_LEN}\n"
while IFS= read line; do
echo "--Running render ${QUEUE_POS} on ${QUEUE_LEN}..."
echo "++" && echo "$line" && echo "++"
eval "${line}"
tail -n +2 "${CONFIG_DIR}/queue" > "${CONFIG_DIR}/queue.tmp" && mv "${CONFIG_DIR}/queue.tmp" "${CONFIG_DIR}/queue"
echo "--Render ended"
QUEUE_POS=`expr $QUEUE_POS + 1`
done < "${CONFIG_DIR}/queue"
exit 0
The problem is that any command makes the loop to work fine (empty line, echo "test"...), but as soon a proper render is loaded, it is launched and finished correctly, but also the loops exists.
I am a newbie so I tried some minor changes to see what effect I got, but nothing change the result.
I commented the command tail -n +2 "${CONFIG_DIR}/queue" > "${CONFIG_DIR}/queue.tmp" && mv "${CONFIG_DIR}/queue.tmp" "${CONFIG_DIR}/queue" or I added/removed IFS= in the while-loop or removed the -r in read command.
Sorry if the question is trivial, but I'm really missing some major part in how it works, so I have no idea even how to search for the solution.
I'll put a sample of a general render in the queue file.
HandBrakeCLI -i "/home/andrea/Videos/done/Rap dottor male e mini me.mp4" -o "/hdd/Render/Output/Rap dottor male e mini me.mkv" -e x265 -q 23 --encoder-preset faster --all-audio -E av_aac -6 dpl2 --all-subtitles -x pmode:pools='16' --verbose=0 2>/dev/null
HandBrakeCLI reads from standard input, which steals the rest of the queue file before read line can see it. My favorite solution to this is to pass the file over something other than standard input, like file descriptor #3:
...
while IFS= read line <&3; do # The <&3 makes it read from FD #3
...
done 3< "${CONFIG_DIR}/queue" # The 3< redirects the file into FD #3
Another way to avoid the problem is to redirect input to the HandBrakeCLI command:
...
eval "${line}" </dev/null
...
There's some more info about this in BashFAQ #89: I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed!
Also, I'm not sure I trust the way you're using tail to remove lines from the queue file as they're executed. I'm not sure it's really wrong, it just looks fragile to me. Also, I'd recommend using lower- or mixed-case variable names, since there are a bunch of all-caps names with special meanings, and re-using one of them by mistake can have weird consequences. Finally, I'd recommend running your script through shellcheck.net, as it'll make some other good recommendations.
[BTW, this question is a duplicate of "Bash script do loop exiting early", but that doesn't have any upvoted or accepted answers.]

How to make Pipe symbol or Grep work in an Android process runtime command?

I am trying to execute the following command;
String cmd = "/system/bin/netstat -"+firstString+" | grep http";
Process process = Runtime.getRuntime().exec(cmd);
Log.d("1:CMD VALUE", cmd);
The log result is 1:CMD VALUE: /system/bin/netstat -a | grep http
However, the output is not getting filtered for the 'http' parameter. The regular "/system/bin/netstat -a" result is what I get for the "/system/bin/netstat -a | grep http`" command as well. Why is this? Is this because of the pipe symbol or the grep command?
Please help.
Thanks.
Other answers on this website were not very clear. Here is the solution.
You need to append "/system/bin/sh -c" before your runtime command for grep to work.
Cheers.

Meaning of am_activity_launch_time?

I am seeking a way to measure launch times of general apps in Android, and happen to know that
adb logcat -b events | grep am_activity_launch_time
might be one answer.
But I failed to find out what duration the command above shows (i.e., from what event to what event). Any help?
You can use this command
cmd0=add logcat -c
to clear the logs and then execute the below command
cmd1 = "grep am_activity_launch_time Example.txt | grep com.example.example| cut -d ',' -f4-4 > Example.csv"
The values are then saved in a csv file.
Then you can the python commands
os.system(cmd0);
os.system(cmd2);
Then use matplotlib to plot the graph from the generated csv files.
axes=plt.gca()
axes.set_xlim([1,20])
axes.set_ylim([0,4000])
plt.title("Performance Analysis ")
plt.ylabel('Time in milliseconds')
plt.xlabel('Number of itirations (DEVICE:Samsung Galaxy Note 4)')
data1=np.genfromtxt("Example.csv)"
plt.plot(data1,label="Example",linewidth=2.0,color='m')
plt.legend(bbox_to_anchor=(1,1),loc=1,borderaxespad=0.)
plt.show()
Once this is done execute this file in the python cmd.
adb logcat -b all | egrep -n --color 'Displayed *'
12461:11-26 22:43:05.316 1110 1167 I ActivityTaskManager: Displayed mobi.goldendict.android.free/mobi.goldendict.android.GoldenDict: +1s494ms
You could measure app launches time in android by this.

Why is nohup still causing a process being run in a shell script to terminate?

I am logging the data coming from top and putting it into a circular set of files. I am not executing top for one set of data and then rerunning for the next set, but instead using a read time out to specify when to go from one log file to the next. This is primarily done this way to remove the startup CPU load cost every time top is executed. The shell script file's name is toplog.sh and looks similar to this:
#!/data/data/com.spartacusrex.spartacuside/files/system/bin/bash
date
echo " Logging started."
fileCmp()
{
test `ls -lc "$1" | sed -n 's/\([^ ]* *\)\{4\}\([0-9]*\).*$/\2/;p'` $2 $3
}
oldest()
{
ls -rc $1 2> /dev/null |head -1
}
file=`oldest /mnt/sdcard/toplog.\*.gz`
echo " Oldest file is $file"
if [ -z "$file" ]; then
x=0
else
file=${file%%.gz}
file=${file##*.}
x=$file
fi
echo " x=$x"
top -d 20 -b | \
while true; do
file=/mnt/sdcard/toplog.$x.gz
while read -t 5 line; do
echo "$line"
done | gzip -c > $file
if fileCmp "$file" -le 300; then
date
echo " Failure to write to file '$file'."
exit
fi
x=$((($x+1)%10))
sleep 14
done
I execute this using nohup so that when the shell dies, this process still runs, like so:
$ nohup ./toplog.sh
But there's a problem. top terminates when I exit the shell session that executed that command, and I'm not exactly sure why. Any ideas?
To clarify, I'm logging on a Android phone. The tools are limited in functionality (i.e. lack some of these switches) and is why I am using top as it contains the output I want.
Version of busybox I'm using is:
BusyBox 1.19.2 (2011-12-12 12:59:36 GMT)
Installed when I installed Terminal IDE.
BTW, this phone is not rooted. I'm trying to track down a failure when my phone responds as if the CPU has spiked and won't go down.
Edit:
Well, I found a workaround. But the reason is a bit hazy. I think it has to do with process management and smells of a bug in the busybox ver that I'm using that was missed during regression testing.
The workaround is to wrap top with a useless loop structure like this: while true; do top; done. Through testing, top never gets killed and never gets respawned, but by wrapping it up, it isn't killed.
Any insights on this?
going to sound stupid, but change your startup command from
nohup ./toplog.sh
to
nohup ./toplog.sh &
the & makes it run as a background process further removing it from the terminal stack.
Running the bash internal command "disown" on your script's process before logging off may prevent it from being signaled.

Filter android logcat ouput for multiple tags

I want to capture logs and dump them into a text file, I am using a perl script to do this. The issue I am running into is that I want to include only certain tags in my logcat command.
I am using
$adbcommand_logcat = "start \"Android-Logcat\" cmd /c \"adb -s $sno logcat -s ^(?=.*?\babc\b)(?=.*?\bxyz\b)(?=.*?\bpqr\b).*$ | -v threadtime | tee ".$mainlog_filename."\"";
but this gives me a blank log instead of the log with tags specified in the regex. If I take out -s after logcat then the regex does not works and log includes everything.
Any help is appreciated.
I got it to work using the following command with egrep.If you don't have the tag try to find the process name and use it instead.
$adbcommand_logcat = "adb -s $sno logcat -v threadtime | egrep \"tag1 or Process 1| tag2 or Process 2\" |tee ".$mainlog_filename;

Categories

Resources