2020年12月12日 星期六

Linux scripts

=========================================================================
= Real-time log inspection and event handling. (Jason Chen, Yet Verified)
=========================================================================
#!/bin/sh

file=/tmp/qq
keyword="jason"
previous_line=0
while true; do
        if [ -f ${file} ]; then
                line=`wc -l ${file} | cut -f1 -d' '`
                if [ ${line} -ne ${previous_line} ]; then
                        matched=`tail -n 1 ${file} | grep ${keyword}`
                        if [ "${matched}" != "" ]; then
                                echo "action here"
                                previous_line=${line}
                        fi
                fi
        fi
        sleep 1
done 


=========================================================================
= Determine whether a process is running or not and make use it to make a conditional shell script?=========================================================================
REF https://askubuntu.com/questions/157779/how-to-determine-whether-a-process-is-running-or-not-and-make-use-it-to-make-a-c
#!/bin/bash

# Check if gedit is running
# -x flag only match processes whose name (or command line if -f is
# specified) exactly match the pattern. 

if pgrep -x "gedit" > /dev/null
then
    echo "Running"
else
    echo "Stopped"
fi

=========================================================================
= How to get the first line of a file in a bash script?=========================================================================
line=$(head -n 1 filename)

=========================================================================
= $var vs "$var"
=========================================================================
$ f="fafafda
> adffd
> adfadf
> adfafd
> afd"

$ echo $f
fafafda adffd adfadf adfafd afd

$ echo "$f"
fafafda
adffd
adfadf
adfafd
afd
=========================================================================
= Single line conditional statements
=========================================================================
if [ ! -f ./some_file ]; then
print "The file was not copied"
exit 1
fi

is equivalent to
[ ! -f ./some_file ] && print "The file was not copied." && exit 1


=========================================================================
= Tricky points
=========================================================================

------------------- Error: [: missing `]' ----------------------------------------------
#!/bin/sh mkubifs_args="-m 4096 -e 253952 -c 2146 -F" ubinize_args="-m 4096 -p 256KiB -s 4096" #Error: [: missing `]' if [ -z "$mkubifs_args"] || [ -z "$ubinize_args" ]; then #if [ -z "$mkubifs_args" ] || [ -z "$ubinize_args" ]; then echo "MKUBIFS_ARGS and UBINIZE_ARGS have to be set, see http://www.linux-mtd.infradead.org/faq/ubifs.html for details" fi

沒有留言: