Not able to validate string in shell script - bash

echo "enter variable"
read var
if[[ ${var} = ^[a-zA-Z][a-zA-Z0-9]{0,25}$ ]];then
echo "valid"
else
echo "invalid"
fi
I'm trying to validate(starting with a character followed by alphanumeric, no special character). 26 characters allowed.
For every input, it gives valid. What am I missing here?

This should work (please note the tilde):
echo "enter variable"
read var
if [[ ${var} =~ ^[a-zA-Z][a-zA-Z0-9]{0,25}$ ]] ; then
echo "valid"
else
echo "invalid"
fi

Related

How to check if the user has entered a single letter?

I am reading a character and want to check if that is single character and is a letter. My code is below:
#!/usr/bin/bash
read -p "Enter something: " char
if [[ ${#char} != 1 && "$char" != *[a-z]* ]]; then
echo "Not a valid input"
else
echo "Its a valid input"
fi
The o/p is below:
[root#host-7 ~]# sh -x t
+ read -p 'Enter something: ' char
Enter something: 1
+ [[ 1 != 1 ]]
+ echo 'Its a valid input'
Its a valid input
While executing the script only first condition is getting executed and its not checking the second condition.
It is not evaluating 2nd condition because first condition is failing as you're entering only 1 character in input and there is && between 2 conditions.
If you enter 2 character input like ab then you'll see both conditions getting evaluated.
You can use -n1 to restrict input to one character only like this:
#!/usr/bin/bash
read -n1 -p "Enter something: " char
echo
if [[ "$char" != *[a-z]* ]];then
echo "Not a valid input"
else
echo "Its a valid input"
fi
And run it as:
bash -x ./t
If you wish to test for a single letter, you can use the POSIX character class [[:alpha:]] or equivalently [a-zA-Z]. No need to check the length or use wildcards as a single bash pattern will only test multiple occurrences of a match when using extglob optional patterns.
read -p "Enter something: " char
if [[ $char != [[:alpha:]] ]]; then
echo "Not a valid input"
else
echo "It's a valid input"
fi
You can simply change the if statement to:
if [[ $char != [a-zA-Z] ]]; then
It will check if $char is a single character and is a letter (a-z,A-Z).
Example:
#!/bin/bash
read -p "Enter something: " char
if [[ $char != [a-zA-Z] ]]; then
echo "Not a valid input"
else
echo "Its a valid input"
fi
Output will be like this:
ab : inavlid
a : valid
1 : invalid
12 : invalid
A : valid
AB : invalid

Check input consists only of numeric characters in shell script

I need to check that the input consists only of numeric characters. I have the code below, but it didn't work properly.
if [[ $1 =~ [0-9] ]]; then
echo "Invalid input"
fi
It should give true only for 678686 not for yy66666.
How about this:-
re='^[0-9]+$'
if ! [[ $Number =~ $re ]] ; then
echo "error: Invalid input" >&2; exit 1
fi
or
case $Number in
''|*[!0-9]*) echo nonnumeric;;
*) echo numeric;;
esac
Try using start/end anchors with your pattern. If you don't, the match succeeds with a part of a test string. Don't forget that you have to use a pattern matching the complete test string if you follow this suggestion.
if [[ $1 =~ ^[0-9]+$ ]]; then
echo "Invalid input"
fi
Check out this SO post for more details.

how to Find a substring in a bash shell script variable

I have a variable like below.
variable = This script is not found
if [[ "$variable" = ~ "not found" ]];
then
echo "Not Found"
else
echo "Its there"
if
while executing im getting below err,
line 4: syntax error in conditional expression
./test.sh: line 4: syntax error near `found"'
./test.sh: line 4: `if [[ "$variable" = ~ "not found" ]]; '
could anyone point me, What im missing here?
LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
echo "matched";
else
echo "no match";
fi
Good Luck ;)
Compare this with your version at the indicated points:
variable="This script is not found" # <--
if [[ "$variable" =~ "not found" ]] # <--
then
echo "Not Found"
else
echo "Its there"
fi # <--
You can't put spaces around = in an assignment, and you need to quote a string literal that has spaces. You don't need a trailing ; if you're going to put then on its own line. And an if-then ends with "fi" not "if".
here is a correct construction of your if statement
if [[ "$variable" =~ "not found" ]]; then
echo "Not Found";
else
echo "Its there";
fi
Input:
line="There\'s a substring to be found!"
if [[ "$line" =~ *"substring"* ]]; then
echo "Not Found";
else
echo "Found!"
fi
Output:
Found!
I have tried below codes which always return same result either in true or false
if [[ "$variable" =~ "not found" ]]; then
echo "Not Found";
else
echo "Its there";
fi

Shell script check if variable contains spaces

I am new to shell scripting. I have a variable containing path to specific file. I want to check if this variable has any spaces in it.
I tried with
if [[ ${VAR} = "${VAR% *}" ]] ; then
echo "contains spaces"
else
echo "doesnot contain spaces"
fi
But it doesn't work. Any help will be really appreciable.
or
case ${VAR} in
*\ * ) echo "VAR=$VAR has at least one space char" ;;
* ) echo "VAR=$VAR has no space chars" ;;
esac
IHTH
Good solution but you need to reverse the conditions. ${VAR% *} strips up to the last space, so if it is equal to ${VAR} then there weren't any spaces.
You should escape the first ${VAR} in "" as well in case it is empty.
if [[ "${VAR}" == "${VAR% *}" ]] ; then
echo "doesn't contains spaces"
else
echo "contains spaces"
fi
Another solution:
echo $VAR | grep ".*\s.*" && echo "Space exists" || echo "No space exists"

How do I prompt a user for confirmation in bash script? [duplicate]

This question already has answers here:
How do I prompt for Yes/No/Cancel input in a Linux shell script?
(37 answers)
Closed 9 years ago.
I want to put a quick "are you sure?" prompt for confirmation at the top of a potentially dangerous bash script, what's the easiest/best way to do this?
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
# do dangerous stuff
fi
I incorporated levislevis85's suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter. You can use one or both of these.
Also, the negated form might look like this:
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi
However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated if should be used.
Explanation:
The read command outputs the prompt (-p "prompt") then accepts one character (-n 1) and accepts backslashes literally (-r) (otherwise read would see the backslash as an escape and wait for a second character). The default variable for read to store the result in is $REPLY if you don't supply a name like this: read -p "my prompt" -n 1 -r my_var
The if statement uses a regular expression to check if the character in $REPLY matches (=~) an upper or lower case "Y". The regular expression used here says "a string starting (^) and consisting solely of one of a list of characters in a bracket expression ([Yy]) and ending ($)". The anchors (^ and $) prevent matching longer strings. In this case they help reinforce the one-character limit set in the read command.
The negated form uses the logical "not" operator (!) to match (=~) any character that is not "Y" or "y". An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: if [[ $REPLY =~ ^[^Yy]$ ]]
use case/esac.
read -p "Continue (y/n)?" choice
case "$choice" in
y|Y ) echo "yes";;
n|N ) echo "no";;
* ) echo "invalid";;
esac
advantage:
neater
can use "OR" condition easier
can use character range, eg [yY][eE][sS] to accept word "yes", where any of its characters may be in lowercase or in uppercase.
Try the read shell builtin:
read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
echo "yaaa";
else
echo "booo";
fi
This way you get 'y' 'yes' or 'Enter'
read -r -p "Are you sure? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
If you are using zsh try this:
read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
Here's the function I use :
function ask_yes_or_no() {
read -p "$1 ([y]es or [N]o): "
case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
y|yes) echo "yes" ;;
*) echo "no" ;;
esac
}
And an example using it:
if [[ "no" == $(ask_yes_or_no "Are you sure?") || \
"no" == $(ask_yes_or_no "Are you *really* sure?") ]]
then
echo "Skipped."
exit 0
fi
# Do something really dangerous...
The output is always "yes" or "no"
It's "no" by default
Everything except "y" or "yes" returns "no", so it's pretty safe for a dangerous bash script
And it's case insensitive, "Y", "Yes", or "YES" work as "yes".
I hope you like it,
Cheers!
This what I found elsewhere, is there a better possible version?
read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
exit
fi
[[ -f ./${sname} ]] && read -p "File exists. Are you sure? " -n 1
[[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
used this in a function to look for an existing file and prompt before overwriting.
echo are you sure?
read x
if [ "$x" = "yes" ]
then
# do the dangerous stuff
fi
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
# do something
fi
I s a short script to read in bash and echo back results.
qnd: use
read VARNAME
echo $VARNAME
for a one line response without readline support. Then test $VARNAME however you want.

Resources