Tuesday, April 14, 2020

Some BASH commands that might be helpful

These are some BASH commands that I use from time to time that help me

Using EVAL to send commands to CLI

In this example, i was trying to send some bash commands to asterisk, but the asterisk syntax wouldn't accept a variable, so i had to run it as a EVAL command
command="asterisk -rx 'sip show peer "$extensionnumber"' | grep Useragent >> /etc/temp.dat"
eval "$command"


So the command is a variable, and everything in quotes gets saved to that variable
Then "EVAL" runs that variable, and all the commands inside it.

Also I wasn't able to reliably work out how to save the output of EVAL to a variable, so i was forced to save it to a temporary file, 'temp.dat'


Checking for variable for Interger value in BASH

If you are looking for a way to check if a variable is integer value heres some code
if expr "$number" : '-\?[0-9]\+$' >/dev/null
      then
         echo "$number is an integer"
      else
         echo "$number is not an integer"
         continue
if

Check if integer variable is between a range of low/high values

if [ "$number" -le "$HighValue" ] && [ "$number" -ge "$LowValue" ]
        then
                echo "$number IN RANGE";
        else
                echo "$number OUT OF RANGE"
                continue
fi

Grep something based on object stored in a variable
So we have a variable with some item(s) that we want to match for
Find everything that matches these values
#if multiple use "'Find1Name\|Find2Name'" and use the \| as a separatorFind="'Find1Name'"
SOMECOMMAND | grep "$Find" 
Find everything that DOES NOT matches these values

#if multiple use "'Find1Name\|Find2Name'" and use the \| as a separator
Find="'Find1Name'"
SOMECOMMAND | grep -v "$Find" 

data="/pathto/filename"
while IFS= read -r lineread
do
  echo "$lineread"
done < "$data"

Use GREP to return a TRUE or FALSE 
if grep -q PATTERN file.txt; then
    echo found
else
    echo not found
fi

Bash Script Sleep or Delay a Specified Amount of Time

s
 for seconds (the default)
m for minutes.
h for hours.
d for days.
sleep 5
sleep 2m
sleep 3h
read -p "Waiting five secs for no reason before continuing...." -t 5
fi





No comments:

Post a Comment

Feel free to leave a comment! If you have any information that you think should be included, please do so here and I'll get it added in.