Bash-common-checks: Difference between revisions

From I Will Fear No Evil
Jump to navigation Jump to search
mNo edit summary
 
(17 intermediate revisions by the same user not shown)
Line 1: Line 1:
<metadesc>Somewhat uncommon bash commands to use in formatting or logic in a bash script.</metadesc>
===Common checks and validations that are a PITA to remember===
===Common checks and validations that are a PITA to remember===
====Is Integer?====
====Is Integer?====
Line 11: Line 12:
fi
fi
</pre>
</pre>
====TCP port check====
* leverage /dev
* use timeout for sanity
* Use for any kind of TCP knock
* do not use FQDN, go by IP
<pre>
IP=192.168.15.100
timeout 1 bash -c "</dev/tcp/${IP}/22"
if [[ $? -ne 0 ]]; then
  echo "ssh port closed at $IP"
else
  echo "ssh port open at $IP"
fi
</pre>
====Find what using inodes====
* use sudo if you are going against /
<pre>
find / -xdev -printf '%h\n' | sort | uniq -c | sort -k 1 -n
</pre>
====Make a banner====
<pre>
skull(){
cat << EIEIO
*************************************************************
*                                                          *
*  .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.      *
*  |                    ______                    |      *
*  |                  .-"      "-.                  |      *
*  |                /            \                |      *
*  |    _          |              |          _    |      *
*  |    ( \        |,  .-.  .-.  ,|        / )    |      *
*  |    > "=._    | )(__/  \__)( |    _.=" <    |      *
*  |    (_/"=._"=._ |/    /\    \| _.="_.="\_)    |      *
*  |          "=._"(_    ^^    _)"_.="          |      *
*  |              "=\__|IIIIII|__/="              |      *
*  |              _.="| \IIIIII/ |"=._              |      *
*  |    _    _.="_.="\          /"=._"=._    _    |      *
*  |  ( \_.="_.="    '--------'    "=._"=._/ )  |      *
*  |    > _.="                            "=._ <    |      *
*  |  (_/                                    \_)  |      *
*  |                                                |      *
*  '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
*                                                          *
*                  Abandon All Hope                        *
*************************************************************/
EIEIO
}
# abandon all hope ye who enter here
skull
</pre>
====Create a CRC16 against string====
* use caution in creating unique values < 65k, as there can be slop and overlap
* Good quick and dirty creation that is reproducible
<pre>
STRING=foo
crc16() {
    while read -r -d "" -n 1 ; do astring+=( "$REPLY" ) ; done <<< "$1"
    cnt=${#1}
    c=65535
    for ((x=0;x<$cnt;x++)); do
        char=$(printf '%d' \'"${1:$x:1}")
        e=$(((c ^ char) & 0x00FF))
        s=$(((e << 4) & 0x00FF))
        f=$(((e ^ s) & 0x00FF))
        r1=$(((c >> 8) ^ (f << 8) ^ (f << 3) ^ (f >> 4)))
        c=$r1
    done
    c=$((c ^ 0xffff))
    echo "$c"
}
crc16 ${STRING}
returns value 26676
</pre>
====Generate random string====
* Great for creating a password
* no reserved chars get generated
<pre>
strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 20 | tr -d '\n'
</pre>
====Create CRC32 from string====
* just to be complete... :)
<pre>
crc32 <(echo "LongString")
1624d322
</pre>
====Generate HEX for string====
* Note this is not able to do the reverse
* No found method to convert the output back to LongString so this is buggy
<pre>
echo -n "LongString"  | cksum | cut -d " "  -f1 | xargs echo printf '%0X\\n' | sh
5751BDB2
</pre>
====Convert first letter to Upper case====
* PROJECT=testproject
<pre>
PROJECT="$(tr '[:lower:]' '[:upper:]' <<< ${PROJECT:0:1})${PROJECT:1}"
echo ${PROJECT}
Testproject
Using tr, this will make the first letter always upper case and ignore the
remainder of the string
</pre>
====Make leading zeros for output ====
* make 2 say 02 instead
* change the % values for things such as decimal precision or more leading numbers
<pre>
$(printf "%02d" 2)
02
</pre>
====Stupid loop I keep forgetting====
Used for renaming television episodes when what you think is a season does not match what tbdb thinks is a season
<pre>
for x in $(seq 1 12); do z=$(( $x + 12 )); y=$(printf "%02d" $x) ; s2='s02e' ; s1='s01e'; if=$(ls ./*$s2$y*) ; fn=$(echo $if | sed "s/$s2$y/$s1$z/") ; mv $if $fn ; done
</pre>
====Function return code examples====
[https://stackoverflow.com/questions/17336915/return-value-in-a-bash-function| Stack Overflow source]
<pre>
#!/bin/bash -e
function func1() {
  return ${1:-0}
}
function func2() {
  local RVAL=""
  RVAL=$(func1 ${1:-0} && echo 0 || echo $?)
  if [[ $RVAL != "0" ]]; then
      echo "Some logic on exit code $RVAL"
      exit $RVAL
  fi
  echo "Some logic on exit code 0"
}
func2 ${1:-0}
Some basic tests
$ ./test.sh
Some logic on exit code 0
$ echo $?
0
$ ./test.sh 128
Some logic on exit code 128
$ echo $?
128
</pre>
====Definition for parameter expansion====
<pre>
In Bash, the syntax return ${1:-0} is a way to return a value from a function, with a default value if the first argument ($1) is not provided. Here's a breakdown of the components:
    ${1:-0}:
        ${1} refers to the first positional parameter passed to the script or function.
        :- is a parameter expansion operator that provides a default value.
        0 is the default value.


    Therefore, ${1:-0} means "use the value of the first argument if it's provided; otherwise, use 0."
    return:
        This command is used within a function to return an exit status. The exit status is a numeric value (0-255) that indicates success (0) or failure (non-zero).
Putting it all together, return ${1:-0} means:
    If the function is called with an argument, return the value of that argument.
    If no argument is provided, return 0.
</pre>
[[Category: Bash]]
[[Category: Bash]]

Latest revision as of 06:31, 8 July 2024

Common checks and validations that are a PITA to remember

Is Integer?

  • Check if a var is an integer
  • support negative as well as positive integer values using extended regex
VAR=123
if [[ ${VAR} =~ ^-?[0-9]+$ ]]; then
  echo "Is integer"
else
  echo "Is not integer"
fi

TCP port check

  • leverage /dev
  • use timeout for sanity
  • Use for any kind of TCP knock
  • do not use FQDN, go by IP
IP=192.168.15.100
timeout 1 bash -c "</dev/tcp/${IP}/22"
if [[ $? -ne 0 ]]; then
  echo "ssh port closed at $IP"
else
  echo "ssh port open at $IP"
fi

Find what using inodes

  • use sudo if you are going against /
find / -xdev -printf '%h\n' | sort | uniq -c | sort -k 1 -n

Make a banner

skull(){
cat << EIEIO
*************************************************************
*                                                           *
*   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.      *
*   |                     ______                     |      *
*   |                  .-"      "-.                  |      *
*   |                 /            \                 |      *
*   |     _          |              |          _     |      *
*   |    ( \         |,  .-.  .-.  ,|         / )    |      *
*   |     > "=._     | )(__/  \__)( |     _.=" <     |      *
*   |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
*   |           "=._"(_     ^^     _)"_.="           |      *
*   |               "=\__|IIIIII|__/="               |      *
*   |              _.="| \IIIIII/ |"=._              |      *
*   |    _     _.="_.="\          /"=._"=._     _    |      *
*   |   ( \_.="_.="     '--------'     "=._"=._/ )   |      *
*   |    > _.="                            "=._ <    |      *
*   |   (_/                                    \_)   |      *
*   |                                                |      *
*   '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
*                                                           *
*                   Abandon All Hope                        *
*************************************************************/
EIEIO
}
# abandon all hope ye who enter here
skull

Create a CRC16 against string

  • use caution in creating unique values < 65k, as there can be slop and overlap
  • Good quick and dirty creation that is reproducible
STRING=foo
crc16() {
    while read -r -d "" -n 1 ; do astring+=( "$REPLY" ) ; done <<< "$1"
    cnt=${#1}
    c=65535
    for ((x=0;x<$cnt;x++)); do
        char=$(printf '%d' \'"${1:$x:1}")
        e=$(((c ^ char) & 0x00FF))
        s=$(((e << 4) & 0x00FF))
        f=$(((e ^ s) & 0x00FF))
        r1=$(((c >> 8) ^ (f << 8) ^ (f << 3) ^ (f >> 4)))
        c=$r1
    done
    c=$((c ^ 0xffff))
    echo "$c"
}
crc16 ${STRING}
returns value 26676

Generate random string

  • Great for creating a password
  • no reserved chars get generated
strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 20 | tr -d '\n'

Create CRC32 from string

  • just to be complete... :)
crc32 <(echo "LongString")
1624d322

Generate HEX for string

  • Note this is not able to do the reverse
  • No found method to convert the output back to LongString so this is buggy
echo -n "LongString"  | cksum | cut -d " "  -f1 | xargs echo printf '%0X\\n' | sh
5751BDB2

Convert first letter to Upper case

  • PROJECT=testproject
PROJECT="$(tr '[:lower:]' '[:upper:]' <<< ${PROJECT:0:1})${PROJECT:1}" 
echo ${PROJECT}
Testproject

Using tr, this will make the first letter always upper case and ignore the
remainder of the string

Make leading zeros for output

  • make 2 say 02 instead
  • change the % values for things such as decimal precision or more leading numbers
$(printf "%02d" 2)
02

Stupid loop I keep forgetting

Used for renaming television episodes when what you think is a season does not match what tbdb thinks is a season

 for x in $(seq 1 12); do z=$(( $x + 12 )); y=$(printf "%02d" $x) ; s2='s02e' ; s1='s01e'; if=$(ls ./*$s2$y*) ; fn=$(echo $if | sed "s/$s2$y/$s1$z/") ; mv $if $fn ; done

Function return code examples

Stack Overflow source

#!/bin/bash -e
function func1() {
   return ${1:-0}
}

function func2() {
   local RVAL=""
   RVAL=$(func1 ${1:-0} && echo 0 || echo $?)
   if [[ $RVAL != "0" ]]; then
      echo "Some logic on exit code $RVAL"
      exit $RVAL
   fi
   echo "Some logic on exit code 0"
}

func2 ${1:-0}
Some basic tests

$ ./test.sh
Some logic on exit code 0
$ echo $?
0
$ ./test.sh 128
Some logic on exit code 128
$ echo $?
128

Definition for parameter expansion

In Bash, the syntax return ${1:-0} is a way to return a value from a function, with a default value if the first argument ($1) is not provided. Here's a breakdown of the components:

    ${1:-0}:
        ${1} refers to the first positional parameter passed to the script or function.
        :- is a parameter expansion operator that provides a default value.
        0 is the default value.

    Therefore, ${1:-0} means "use the value of the first argument if it's provided; otherwise, use 0."

    return:
        This command is used within a function to return an exit status. The exit status is a numeric value (0-255) that indicates success (0) or failure (non-zero).

Putting it all together, return ${1:-0} means:

    If the function is called with an argument, return the value of that argument.
    If no argument is provided, return 0.