Bry*_*yan 2 bash awk shell-script
我收到上述语法错误,但我无法破译它出了什么问题。我正在尝试在 BASH 中执行浮点值。
因此我使用了这个名为 的命令awk来实现目标。
while $empty; do
empty=false
echo -n "Price : "; read getPrice
#float value using awk
awk 'BEGIN{if ('$getPrice'>'0') exit 1}'
if [ $? -eq 1 ]; then
PRICE[$COUNT]=$getPrice;
else
empty=true
echo "Please put in the correct price figure!"
fi
done
Run Code Online (Sandbox Code Playgroud)
但是,我收到了这个错误
awk:第 1 行:> 处或附近的语法错误
当我没有向getPrice变量输入任何值时发生此错误。但是,当我输入一些值时它工作正常>0。经过深思熟虑,我还是不明白语法有什么问题。问候。
Awk 脚本中出现语法错误的原因是当$getPrice为空时,脚本实际上只是
BEGIN{if (>0) exit 1}
Run Code Online (Sandbox Code Playgroud)
将 shell 变量作为 Awk 变量导入到 Awk 脚本中的正确方法是使用-v:
awk -vprice="$getPrice" 'BEGIN { if (price > 0) exit 1 }'
Run Code Online (Sandbox Code Playgroud)
我还查看了脚本中的控制流程,$empty您可以在输入正确的价格后退出循环,而不是使用变量:
while true; do
read -p 'Price : ' getPrice
# compare float value using awk
if awk -vprice="$getPrice" 'BEGIN { if (price <= 0) exit(1) }'
then
PRICE[$COUNT]="$getPrice"
break
fi
echo 'Please put in the correct (positive) price figure!' >&2
done
Run Code Online (Sandbox Code Playgroud)
评论后的补充细节:
如果输入的值不是数字或者为负数,则应提醒用户输入无效。我们可以测试输入值中是否存在不应该出现的字符(除了数字 0 到 9 和小数点之外的任何字符):
while true; do
read -p 'Price : ' getPrice
if [[ ! "$getPrice" =~ [^0-9.] ]] && \
awk -vprice="$getPrice" 'BEGIN { if (price <= 0) exit(1) }'
then
PRICE[$COUNT]="$getPrice"
break
fi
echo 'Please put in the correct (positive) price figure!' >&2
done
Run Code Online (Sandbox Code Playgroud)