Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 1425  / 3 Years ago, wed, august 18, 2021, 7:13:13

Hi I am trying to write a bash script in which the input is checked to see if it contains an @ symbol, I'm am relatively new to bash so please forgive any/all errors!
So far I have:



var1="@"
var2="INPUT"

echo "input"
read INPUT

if [[ "$var2" == "$var1" ]]; then
echo "pass"
else
echo "fail"
fi

More From » bash

 Answers
0

This bash code reads input and signals "Pass" if the input contains an @ symbol:



read -p "Input: " var
[ "${var//[^@]/}" ] && echo Pass || echo Fail


Notes:




  • [ "$var" ] is a bash test. It returns true if the string $var is non-empty.


  • One of bash's features is pattern substitution. It looks like ${var//pattern/string}. It replaces every occurrence of pattern in var with string. In our case, pattern is [^@] which is a regular expression which matches every character except @. Thus ${var//[^@]/} returns an empty string unless var contains at least one @.


  • We combine the above two:



    [ "${var//[^@]/}" ]


    This test succeeds only if ${var//[^@]/} is non-empty and ${var//[^@]/} is non-empty only if var contains at least one @.




Using an explicit if-then-else:



read -p "Input: " var
if [ "${var//[^@]/}" ]
then
echo Pass
else
echo Fail
fi


POSIX Shell



The following works under dash (/bin/sh) and should work under any POSIX shell:



printf "Input: "
read var
case "$var" in
*@*) echo Pass
;;
*) echo Fail
;;
esac


The POSIX shell does not support the -p option to read. So, a combination of printf and read are used instead. Also, lacking advanced variable expansion features of bash, the case statement can be used for glob matching.



Android Shell



Using the default shell on my android, the following works:



echo -n "Input: "; read var
if ! [ "${var//@/}" = "$var" ]
then
echo Pass
else
echo Fail

[#22571] Wednesday, August 18, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rieency

Total Points: 299
Total Questions: 116
Total Answers: 111

Location: Wales
Member since Tue, Dec 14, 2021
2 Years ago
;