Until user input equals something do - bash

So somebody showed me how to use condition(s) to test if a user had typed input for a password.
I wanna take a their example a step further and use a loop (at least thats what I think it's call).
Here is their example:
read -s -p "Enter new password: " NEWPASS
if test "$NEWPASS" = ""; then
echo "Password CAN NOT be blank re-run sshd_config"
exit 1;
fi
Instead of exiting the script I want it to keep asking for the input until there is some.
I wanna make a statement like this but I was doing it wrong:
(Now using top example)
The user is given a chance to enter new password and fill the variable value.
read -s -p "Enter new password:" NEWPASS
echo ""
The next portion checks the variable to see if it contains a value, while the value is null it request the user to fill the value indefinitely. ( a loop)
while [[ -z "$NEWPASS" ]]; do
echo ""
echo "Password CAN NOT be blank"
echo ""
read -s -p "Enter new password:" NEWPASS;
echo ""
done
This line searches a file containing a set of variables used by another file. It then searches the file for a line containing PASS=.* (.* meaning anything) then writes PASS=$NEWPASS ($NEWPASS being variable)
sed -i -e"s/^PASS=.*/PASS=$NEWPASS/" /etc/sshd.conf
Thank you for all the help, I'm going to use this and learn from it.

This while loop should work:
while [[ -z "$NEWPASS" ]]
do
read -s -p "Enter new password: " NEWPASS
done

while read -s -p 'Enter new password: ' NEWPASS && [[ -z "$NEWPASS" ]] ; do
echo "No-no, please, no blank passwords!"
done

Related

Bash function with IF statement

Is there a way to have a function which will take a -y flag and answer yes to all the questions instead of the user doing Y to each question, After specifying what database to use ?
when running script.sh I would like to run it as ./script.sh -y which will ask me what database to use and then do YES to all the questions:
#Database selection
echo "Enter the database name: "
read databasename
#Questions
read -r -p "Do you want to anonymise Customer Forename/Surname ? [y/N] " response1
if [[ $1 = "-y" ]] || [[ "$response1" =~ ^([yY][eE][sS]|[yY])$ ]]
then
pv forenamesurname.sql | mysql "$databasename"
echo "Anonym OK"
else
echo "Anonym not OK"
fi
exit
Your code does not work correctly, because you are always execute the read, even if a paramter is supplied.
I would eader replace the read statement completely by
response1=${1:--n} # Sets response1 to, i.e., -y
response1=${response1:1:1} # Sets response1 to just y
which sets it to the first parameter, respectively to -n if no parameter has been passed. Alternatively, you could do a
if [[ -n ${1:-} ]] # Do we have a parameter?
then
response=${1:1:1}
else
read -r -p "Do you want to anonymise Customer Forename/Surname ? [y/N] " response1
fi
which is nearly the same, but asks explicitly for y/n, if no parameter has been supplied.

Bash script that asks for password to view passwords file

I'm trying to create a bash script that asks for password when you try to see the password file, but I'm stucked. This is my code:
#!/bin/bash
# Read Password
echo -n Password:
read -s PASSWORD
passwords() {
echo "
PASSWORDS
"
}
if [ "$PASSWORD"="root" ]; then
passwords
exit
else
echo "Wrong password"
exit
fi
I've tried a lot of things, for example if [ "$PASSWORD"!="root" ] instead of else but none of them worked.
Here is a shorter version:
#!/bin/bash
passwords(){
echo "PASSWORDS"
}
## Read Password
read -p "Enter password: " -s PASSWORD
desired_password="root"
[ "$PASSWORD" == "$desired_password" ] && passwords || echo "Wrong password"
As #vdavid said, you can add a space around the equal sign or even better, as you have bash shell, it is recommended to use double-bracket for your if statement. Check this: Is there any difference between '=' and '==' operators in bash or sh
Also you can add:
printf "/n" so your script will behave like a typical Linux prompt for password - information will output in new line
non-zero exit code in case of wrong password (exit 1)
Basically, after those improvements code looks like this:
#!/bin/bash
# Read Password
echo -n Password:
read -s PASSWORD
printf "\n"
passwords() {
echo "PASSWORDS"
}
if [[ "$PASSWORD" == "root" ]]; then
passwords
exit 0
else
echo "Wrong password"
exit 1
fi
Note that I used "==" instead of "=", but for double-bracket they both do the same job.

why is a bash read prompt not appearing when a script is run?

I have a bash script that prompts the user for different information based on what they're trying to do. The prompts are usually done with read -p. Usually it works just fine, the user sees what is being asked, enters what they need to enter, and everything does what it needs to do.
See the following (sanitized) snippet of a function in the script:
#!/bin/bash
function_name() {
if [ "$this_value" == "default" ];then
echo "Value set to default."
read -p "Enter desired value here: " desired_value
desired_value=${desired_value^^}
if [ "${#desired_value}" != 3 ] ;then
echo "$desired_value is an invalid entry."
exit 1
fi
if [ "$desired_value" != "$(some command that returns something to compare against)" ];then
echo "$desired_value is an invalid entry."
exit 1
fi
read -p "You entered $desired_value. Is this correct? [y/N] " reply
reply=${reply,,}
case "$reply" in
y|yes)
$some command that does what I want it to do
;;
*)
echo "User did not enter yes"
exit 1
;;
esac
fi
}
Usually the Enter desired value here and is this correct? lines appear just fine. But in a few instances I've seen, for some reason the read prompt is just blank. A user will see the following:
./script.bash
##unrelated script stuff
##unrelated script stuff
Value set to default.
user_entered_value_here
User did not enter yes. Exiting.
This is a real example that just happened that finally made me come here to ask what is going on (and I modified appropriately to make it an SO post).
What's happening is these two blank lines appear instead of the read -p text. For the first one, the user entered user_entered_value_here because they already know what is supposed to be entered there even without the read prompt. The second one, the Y/N prompt, they don't know, so they see it apparently hanging, and hit Enter instead of y, causing it to trigger the * case option.
I don't understand why the read -p text is not appearing, and especially why it's appearing for most users but not all users. I suspect there's some kind of environmental setting that causes this, but for the life of me I can't figure out what. This is being run only on RHEL 6.2, under bash 4.1.2.
I looked at the man of bash to catch some kind of detail about the read built-in. It is specified that -p option displays the "prompt on standard error, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal".
Let's consider the simple script input.sh:
#!/bin/bash
read -p "Prompt : " value
echo The user entered: "$value"
Example of execution:
$ ./input.sh
Prompt : foo
The user entered: foo
If stderr is redirected:
$ ./input.sh 2>/dev/null
foo
The user entered: foo
If the input is a pipe
$ echo foo | ./input.sh
The user entered: foo
If the input is a heredoc
$ ./input.sh <<EOF
> foo
> EOF
The user entered: foo
Rewrote your script with shell agnostic grammar and fixed some errors like comparing the string length with a string comparator != = rather than a numerical comparator -ne -eq:
#!/usr/bin/env sh
this_value=default
toupper() {
echo "$1" | tr '[:lower:]' '[:upper:]'
}
function_name() {
if [ "$this_value" = "default" ]; then
echo "Value set to default."
printf "Enter desired value here: "
read -r desired_value
desired_value=$(toupper "$desired_value")
if [ "${#desired_value}" -ne 3 ]; then
printf '%s is an invalid entry.\n' "$desired_value"
exit 1
fi
if [ "$desired_value" != "$(
echo ABC
: some command that returns something to compare against
)" ]; then
echo "$desired_value is an invalid entry."
exit 1
fi
printf 'You entered %s. Is this correct? [y/N] ' "$desired_value"
read -r reply
reply=$(toupper "$reply")
case $reply in
'y' | 'yes')
: "Some command that does what I want it to do"
;;
*)
echo "User did not enter yes"
exit 1
;;
esac
fi
}
function_name

If / Else statement issues in bash scripting

I recently created a different thread with an issue concerning a for loop in a bash script I was writing for my GCSE coursework. I have another issue with the same bash script (however it has evolved a fair bit since last time).
Here is the code:
#!/bin/bash
# A script that creates users.
uerror='^[0-9]+$'
echo "This is a script to create new users on this system."
echo "How many users do you want to add? (in integer numbers)"
read am
echo " "
if [[ $am =~ $uerror ]] ; then
echo "ERROR: Please use integer numbers."
echo "Please re-enter the amount."
read am ;
else
echo " "
for i in $(seq "$am")
do
echo "Enter a username below:"
read usern
sudo useradd $usern
sudo passwd $usern
echo " "
echo "User $i '$usern' added."
echo " "
echo "What group do you want to add $usern to?"
read group
sudo usermod $usern -aG $group
echo "$usern added to $group"
echo " "
echo "-------------------"
echo " "
done
fi
The issue is in the if statement. It's purpose is to stop users entering anything other than an integer number. But for some reason, I don't seem to be able to capture the input from the read am part. Instead the script skips straight onto the for loop where the $(seq "$am") obviously will have issues comprehending an input that is not a number.
The output from this error is as follows.
seq: invalid floating point argument
However, I don't think this is relevant because as far as I can tell, the issue is with the if / else statement.
If anyone could point me in the right direction of what I need to do to fix this, I would be greatly appreciative.
I'd also like to iterate that I am still learning how to write bash scripts (and not in a particularly organised manner) so I've probably made a very simple mistake. Apologies for that.
Thanks,
Callum.
EDIT: I mistyped an echo message, I've now changed that so it actually makes sense.
If you want to read in a number and make sure it is a number use a while loop:
while read -p 'type a number:' n ; do
# Exit the loop if the input is a number
[[ "$n" =~ ^[0-9]+$ ]] && break
echo "This was not a number! Don't trick me!"
done
# Now can use `seq`
seq "$n"
The if statement in your example would do the completely the wrong thing. It checks if the input is a number and in that case asks for the input again and exits the script. If you don't type a number, it uses the (wrong) input in the else branch.
Replace your whole file with this:
#!/bin/bash
# A script that creates users.
uerror='^[0-9]+$'
echo "This is a script to create new users on this system."
echo "How many users do you want to add? (in integer numbers)"
read am
echo " "
while true; do
if [[ $am =~ $uerror ]] ; then
break;
else
echo "Must be integer"
echo "Please re-enter: "
read am ;
fi
done
for i in $(seq "$am")
do
echo "Enter a username below:"
read usern
sudo useradd $usern
sudo passwd $usern
echo " "
echo "User $i '$usern' added."
echo " "
echo "What group do you want to add $usern to?"
read group
sudo usermod $usern -aG $group
echo "$usern added to $group"
echo " "
echo "-------------------"
echo " "
done

how do i assigne out put of command as variable

Hi i am very new to scripting. please My apologizes if i am pointing in wrong way.
I am trying to develop a script which take the backup of given path. Below is my script.
The problem I facing is that I am trying to assign a variable "s" to an command "mkdir" and it do not work. Please help me,how i can correct this syntax?
#!/bin/bash
# to back up the given folder "
i="`date | awk '{ print $1$2$4}'`"
echo " please enter the full path of folder you want to back up"
read foldern
echo " $foldern is of `du -sh $foldern`. Do you want to back up this folder"
echo "yes / no"
read ans
if [ $ans = yes ]
then
echo " enter the back up folder name"
read bpn
s=$(mkdir $bpn$i) # here I am trying to assign a variable "s" for out put of mkdir but dosent work Please help me #
echo $s
cp -R "$foldern" "$s"
else
echo "no back up is taken"
fi
mkdir does not create an output or print the directory it has created. Manually create the string instead:
s=$bpn$i
mkdir -- "$s"
echo "$s"
-- is an optional option-argument separator so files beginning with - is not misinterpreted as a bad option to mkdir.
Adding -p can also be helpful if you don't want mkdir to show an error if the directory already exists.
mkdir -p -- "$s"
Suggestion:
#!/bin/bash
# To back up the given folder.
date=$(date | awk '{ print $1$2$4}') ## Consider date=$(date '+%F-%T')
read -p "Please enter the full path of folder you want to back up: " folder_name
size=$(du -sh "$folder_name")
read -p "$folder_name is of $size. Do you want to back up this folder (Yes/No)? "
if [[ $ans == [yY][eE][sS] ]]; then
read -p "Enter the back up folder name: " backup_name
backup_name+=$date
echo "$backup_name"
mkdir -p "$backup_name" && cp -R "$folder_name" "$backup_name"
else
echo "No back up is taken."
fi

Resources