#! /bin/bash
# test.bash is trying to redirect output of $? which can be either 0 or non zero to variable. But following script gives only blank output to flag variable. Can you assist how to redirect $? value to variable? Why is it showing blank?
#check for 5 digit argument
read -p "Enter 5 digit Account Number `echo $'\n> '`" accNum
echo $accNum | grep "^[0-9][0-9][0-9][0-9][0-9]$" > flag
echo $? > flag
echo "flag is $flag"
以下是我的 test.bash:
~$ bash test.bash
Enter 5 digit Account Number
> asdf
flag is
~$
~$ bash test.bash
Enter 5 digit Account Number
> 11111
flag is
~$
答案1
我认为您想要实现的目标是:
#!/bin/bash
# Check for 5 digit argument.
read -p "Enter 5 digit Account Number `echo $'\n> '`" accNum
echo $accNum | grep -q '^[0-9][0-9][0-9][0-9][0-9]$'
flag=$?
echo "flag is $flag"
注意:
- 不需要重定向输出;
- 分配给
flag
; - 正则表达式用单引号引起来,而不是双引号,因为它包含
$
;并且 grep -q
如果正则表达式匹配则抑制输出。