gaboshlib/g_num_is_between.sh aktualisiert

This commit is contained in:
olli 2023-11-07 13:02:12 +01:00
parent 0702ecfeb5
commit 3e981f64dd

View File

@ -1,47 +1,54 @@
function g_num_is_between {
function g_calc {
local f_num=$1
local f_between1=$2
local f_between2=$3
# Check for integer (can be done with bash itself)
if [[ ${f_num} =~ ^[0-9]+$ ]] && [[ ${f_between1} =~ ^[0-9]+$ ]] && [[ ${f_between2} =~ ^[0-9]+$ ]]
# Use bc in backround for multiple bc's running much faster
if [ -z "${g_bc_running}" ]
then
# Check which is the low (from) and the high (to) number
if [ "${f_between1}" -lt "${f_between2}" ]
then
local f_from=${f_between1}
local f_to=${f_between2}
else
local f_from=${f_between2}
local f_to=${f_between1}
fi
# Check if given number is in or out range
if [ ${f_num} -lt ${f_from} ] || [ ${f_num} -gt ${f_to} ]
then
return 1
else
return 0
fi
g_rnd=$RANDOM
mkdir -p ${g_tmp}/${g_rnd}
[ -p ${g_tmp}/${g_rnd}/bc-in ] || mkfifo ${g_tmp}/${g_rnd}/bc-in
[ -p ${g_tmp}/${g_rnd}/bc-out ] || mkfifo ${g_tmp}/${g_rnd}/bc-out
[ -p ${g_tmp}/${g_rnd}/bc-sed-in ] || mkfifo ${g_tmp}/${g_rnd}/bc-sed-in
[ -p ${g_tmp}/${g_rnd}/bc-sed-out ] || mkfifo ${g_tmp}/${g_rnd}/bc-sed-out
# bc stream channel
{ bc -ql <${g_tmp}/${g_rnd}/bc-in 2>&1 >${g_tmp}/${g_rnd}/bc-out & } 2>/dev/null
exec 3>${g_tmp}/${g_rnd}/bc-in 4<${g_tmp}/${g_rnd}/bc-out
# sed stream channel
{ sed -su 's/^\./0./; s/^-\./-0./' <${g_tmp}/${g_rnd}/bc-sed-in >${g_tmp}/${g_rnd}/bc-sed-out & } 2>/dev/null
exec 5>${g_tmp}/${g_rnd}/bc-sed-in 6<${g_tmp}/${g_rnd}/bc-sed-out
g_bc_running="true"
fi
# Check for valid number
g_num_valid_number "$f_num" "$f_between1" "$f_between2" || return 1
# Check which is the low (from) and the high (to) number
if [ $(g_calc "${f_between1} < ${f_between2}") -ne 0 ]
then
local f_from=${f_between1}
local f_to=${f_between2}
else
local f_from=${f_between2}
local f_to=${f_between1}
fi
# Check if given number is in or out range
if [ $(g_calc "${f_num} < ${f_from}") -ne 0 ] || [ $(g_calc "${f_num} > ${f_to}") -ne 0 ]
# do bc
echo "scale=8; $@" >&3
local g_bc_out
if ! read -t 0.1 g_bc_out <&4
then
g_traceback "$@"
( exec 3<&- ) 2>/dev/null
( exec 4<&- ) 2>/dev/null
( exec 5<&- ) 2>/dev/null
( exec 6<&- ) 2>/dev/null
unset g_bc_running
return 1
else
return 0
fi
# do sed
echo ${g_bc_out} >&5
local g_sed_out
if ! read -t 0.1 g_sed_out <&6
then
g_traceback "$@"
( exec 3<&- ) 2>/dev/null
( exec 4<&- ) 2>/dev/null
( exec 5<&- ) 2>/dev/null
( exec 6<&- ) 2>/dev/null
unset g_bc_running
return 1
fi
# echo result
echo ${g_sed_out}
}