我有一个学校的作业,这是创建一个脚本,可以计算任何长度的数学方程使用操作的顺序。我在这方面遇到了一些麻烦,最终找到了关于here-string的信息。该脚本最大的问题似乎是错误检查。我尝试使用$?检查bc的输出,但无论是成功还是失败,结果都是0。作为响应,我现在尝试将here-string的输出存储到一个变量中,然后我将使用regex检查输出是否以数字开头。下面是我希望存储在变量中的代码片段,后面是我的脚本的其余部分。
#!/bin/bash
set -f
#the here-string bc command I wish to store output into variable
cat << EOF | bc
scale=2
$*
EOF
read -p "Make another calculation?" response
while [ $response = "y" ];do
read -p "Enter NUMBER OPERATOR NUMBER" calc1
cat << EOF | bc
scale=2
$calc1
EOF
read -p "Make another calculation?" response
done
~发布于 2017-03-14 06:50:11
这应该能起到作用:
#!/bin/sh
while read -p "Make another calculation? " response; [ "$response" = y ]; do
read -p "Enter NUMBER OPERATOR NUMBER: " calc1
result=$(bc << EOF 2>&1
scale=2
$calc1
EOF
)
case $result in
([0-9]*)
printf '%s\n' "$calc1 = $result";;
(*)
printf '%s\n' "Error, exiting"; break;;
esac
done示例运行:
$ ./x.sh
Make another calculation? y
Enter NUMBER OPERATOR NUMBER: 5+5
5+5 = 10
Make another calculation? y
Enter NUMBER OPERATOR NUMBER: 1/0
Error, exiting请注意,您可以在没有像这样的here-document的情况下执行此操作:
result=$(echo "scale=2; $calc1" | bc 2>&1)https://stackoverflow.com/questions/42774682
复制相似问题