How to detect file ends in newline?

Here is a useful bash function: function file_ends_with_newline() { [[ $(tail -c1 “$1” | wc -l) -gt 0 ]] } You can use it like: if ! file_ends_with_newline myfile.txt then echo “” >> myfile.txt fi # continue with other stuff that assumes myfile.txt ends with a newline

number of tokens in bash variable

The $# expansion will tell you the number of elements in a variable / array. If you’re working with a bash version greater than 2.05 or so you can: VAR=’some string with words’ VAR=( $VAR ) echo ${#VAR[@]} This effectively splits the string into an array along whitespace (which is the default delimiter), and then … Read more

jq returning null as string if the json is empty

Something useful I found for shell scripts was: jq ‘.foo // empty’ Which returns the match if successful, and the empty string if unsuccessful. So in bash I use: addr=$(./xuez-cli getnetworkinfo | jq -r ‘.localaddresses[0].address // empty’) if [[ ! -z “$addr” ]]; then # do something fi Ref: https://github.com/stedolan/jq/issues/354#issuecomment-43147898 https://unix.stackexchange.com/questions/451479/jq-print-for-null-values

Split string with bash with symbol

Using Parameter Expansion: str=”test1@test2″ echo “${str#*@}” The # character says Remove the smallest prefix of the expansion matching the pattern. The % character means Remove the smallest suffix of the expansion matching the pattern. (So you can do “${str%@*}” to get the “test1” part.) The / character means Remove the smallest and first substring of … Read more