Skip to content

Instantly share code, notes, and snippets.

@xie-qianyue
Created July 22, 2018 05:30
Show Gist options
  • Save xie-qianyue/e254a2bfc0cdabd35035a9a91ccc97b8 to your computer and use it in GitHub Desktop.
Save xie-qianyue/e254a2bfc0cdabd35035a9a91ccc97b8 to your computer and use it in GitHub Desktop.
grep return value and /dev/null redirection
echo -en "Please guess the magic number: "
read X
echo $X | grep "[^0-9]" > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
# If the grep found something other than 0-9
# then it's not an integer.
echo "Sorry, wanted a number"
else
# The grep found only 0-9, so it's an integer.
# We can safely do a test on it.
if [ "$X" -eq "7" ]; then
echo "You entered the magic number!"
fi
fi
@xie-qianyue
Copy link
Author

xie-qianyue commented Jul 22, 2018

Note that grep has a -q argument to not output the matched text (but only return the exit status code). So you don't need to redirect the std output to /dev/null.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment