Shellが実現したいくつかの数学演算のカスタム関数の共有
5254 ワード
最近はスクリプトで計算が必要で、毎回awkを使うのが面倒なので、awkの加減乗除をカプセル化し、直接source math.shを呼び出すたびにできます.後で修正するときに忘れないように、いくつかのポイントを指摘します. 1、2つの数字を数字かどうかを判断し、awkでマッチングする2、2つのパラメータをループチェック(2回のチェックを書くのは不器用)し、変数の参照${!para}を使用する必要がある.
#!/bin/bash
############################
# shell + - × /
# :2014-01-18
# :[email protected]
# : version 1.0
# : 2
############################
#####################
#function is_Digit()
#
#
#
# , 1, 0
######################
functionis_Digit()
{
ref=`echo$1 | awk'{print($0~/^[+-]?[0-9]?*(\.[0-9]*)?$/)?"digit":"string"}'`
if[ "$ref"== "digit"];then
return0;
else
return1;
fi
}
###################
#function multiply()
#
#
#
# ${!para}
# , C return,
# ,echo
###################
functionmul()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%d
",num_a*num_b}'`;
echo$ref;
}
########################
#function div()
# ,
########################
functiondiv()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%d
",num_a/num_b}'`;
echo$ref;
}
########################
#function add()
# ,
########################
functionadd()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%d
",num_a+num_b}'`;
echo$ref;
}
########################
#function sub()
# ,
########################
functionsub()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%d
",num_a-num_b}'`;
echo$ref;
}
###################
#function mul_f()
#
#
#
# ${!para}
# , C return,
# ,echo
###################
functionmul_f()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%0.2f
",num_a*num_b}'`;
echo$ref;
}
########################
#function div_f()
# ,
########################
functiondiv_f()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%0.2f
",num_a/num_b}'`;
echo$ref;
}
########################
#function add_f()
# ,
########################
functionadd_f()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%0.2f
",num_a+num_b}'`;
echo$ref;
}
########################
#function sub_f()
# ,
########################
functionsub_f()
{
for(( i=1;i<3;i++ ))
do
pa="$i"
ifis_Digit ${!pa}
then
continue;
else
echo"$pa isn't a number";
return0;
fi
done
ref=`awk-vnum_a=$1 -vnum_b=$2 'BEGIN{printf "%0.2f
",num_a-num_b}'`;
echo$ref;
}