我试图自学bash脚本,并且我试图学习如何在复合测试命令([[]])和测试([])之间交替。
使用我从中学习的书,我尝试使用test而不是[[]]重新创建以下程序。
#!/bin/bash
# read-validate: valiate input
invalid_input()
{
echo "Invalid input '$REPLY'" >&2
exit 1
}
read -p "Enter a single item > "
#input is empty (invalid)
[ -z $REPLY ] && invalid_input
#input is multiple items
(( $(echo $REPLY | wc -w) > 1 )) && invalid_input
# is input a valid filename?
if [[ $REPLY=~ ^[-[:alnum:]\._]+$; then
echo "'$REPLY is a valid filename."
if [ -e $REPLY ]; then
echo "And file '$REPLY' exists."
else
echo "However, file '$REPLY' does not exist."
fi
#is input a floating point number?
if [[ $REPLY =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
echo "'$REPLY' is a floating point number."
else
echo "'$REPLY' is not a floating point number."
fi
# is input an integer?
if [[ $REPLY =~ ^-?[[:digit:]]+$ ]]; then
echo "'$REPLY' is an integer."
else
echo "'$REPLY' is not an integer."
fi
else
echo "The string '$REPLY' is not a valid filename."
fi
我的问题始于尝试使用正则表达式搜索浮点数。
#!/bin/bash
# read-validate: valiate input
invalid_input()
{
echo "Invalid input '$REPLY'" >&2
exit 1
}
read -p "Enter a single item > "
valid_fname=$(egrep ^[-[:alnum:]\._]+$ <<< "$REPLY" | wc -m)
valid_float=$(egrep ^-?[[:digit:]]*\.[[:digit:]]+$ <<< "$REPLY" | wc -w)
#input is empty (invalid)
[ -z $REPLY ] && invalid_input
#input is multiple items
(( $(echo $REPLY | wc -w) > 1 )) && invalid_input
# is input a valid filename?
if [ "$valid_fname" -gt 0 ]; then
echo "'$REPLY is a valid filename."
if [ -e $REPLY ]; then
echo "And file '$REPLY' exists."
else
echo "However, file '$REPLY' does not exist."
fi
#is input a floating point number?
if [ "$valid_float" -gt 0 ]; then
#if [[ $REPLY =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
echo "'$REPLY' is a floating point number."
else
echo "'$REPLY' is not a floating point number."
fi
else
echo "The string '$REPLY' is not a valid filename."
fi
由于某些原因,即使正则表达式中包含\.
,egrep也不会费心寻找小数点。这导致程序获取整数并将它们验证为浮点数。奇怪的是,单个数字不会被验证为浮点(0-9)。但是,两位数和以后的整数被验证为浮点数。我不知道为什么会这样。