How do I read user input into a variable in Bash? - bash

How do I read user input into a variable in Bash?
fullname=""
# Now, read user input into the variable `fullname`.

Use read -p:
# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user
If you like to get the user's confirmation:
read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
You should also quote your variables to prevent pathname expansion and word splitting with spaces:
# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"

Yep, you'll want to do something like this:
echo -n "Enter Fullname: "
read fullname
Another option would be to have them supply this information on the command line. Getopts is your best bet there.
Using getopts in bash shell script to get long and short command line options

Try this
#/bin/bash
read -p "Enter a word: " word
echo "You entered $word"

Also you can try zenity !
user=$(zenity --entry --text 'Please enter the username:') || exit 1

https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html
One line is read from the standard input, or from the file descriptor
fd supplied as an argument to the -u option, split into words as
described above in Word Splitting, and the first word is assigned to
the first name, the second word to the second name, and so on. If
there are more words than names, the remaining words and their
intervening delimiters are assigned to the last name.
echo "bash is awesome." | (read var1 var2; echo -e "Var1: $var1 \nVar2: $var2")
bash will be var1
is awesome will be var2
echo -e enable interpretation of backslash escapes from ubuntu manual.
so the full code can be:
echo -n "Enter Fullname: "
read fullname
echo "your full name is $fullname."
echo -n "test type more than 2 word: "
read var1 var2; echo -e
read var1 var2; echo -e "Var1: $var1 \nVar2: $var2")

Maximally portable (bash, zsh, ...):
printf "%s" "Enter fullname: "
read fullname
This is the most portable way to read with prompt. Methods such as read -p and echo -n are more likely to fail depending on the shell.

Related

Is there a concise way to conditionally set the variable that read will assign to?

Is there a way to prompt the user and read on the same line but make the variable that's read conditional?
Something like this:
read -p "Enter input: " [ if some condition=true varA else varB ]
The manual pages for read don't seem to suggest that this is possible.
I wouldn't try to do this in one line.
if ...; then
var=varA
else
var=varB
fi
read -p "Enter input" "$var"
The argument to read is the name of a variable, so you can store that name in another variable to be expanded when you call read.
Alternately, just read the input into a fixed variable, then assign its value to the correct variable.
read -p "Enter input" response
if ...; then
varA=$response
else
varB=$response
fi
Just output the string...
read -p "Enter input: " "$(if some condition=true; then echo varA; else echo varB; fi)"

New Employee bash script

I am new to bash scripting. I have a script that i am working on for a school project and its not working as expected. I keep receiving a error on my if then statements.
#!/bin/bash
echo –e “Would you like to add a new employee’s information? y/n \n”
read EMPLOYEE
if [ $EMPLOYEE = “y” –o $EMPLOYEE = “Y” ]
then
echo –e “Please enter employee’s first name  \c”
read FIRST
echo –e “Please enter employee’s last name  \c”
read LAST
echo –e “Please enter empolyee’s ID  \c”
read ID
echo –e “$FIRST\t$LAST\t$ID” >> database
fi
echo –e “Would you like to search for an employee? y/n \n”
read SEARCH
if [ $SEARCH = “y” –o $SEARCH = “Y” ]
then
echo –e “Enter the first name, last name or employee ID to search for.  \c”
read WORD
grep “$WORD” database
fi
With even a bash version 3 the following should work as you intended and be somehow shellitical correct ;-)
#!/bin/bash
printf "Would you like to add a new employee’s information? y/n \n"
read -r EMPLOYEE
if [ "$(tr '[:upper:]' '[:lower:]' <<<"$EMPLOYEE")" = "y" ]
then
printf "Please enter employee’s first name : \c"
read -r FIRST
printf "Please enter employee’s last name : \c"
read -r LAST
printf "Please enter empolyee’s ID : \c"
read -r ID
printf "%s\t%s\t%s" "$FIRST" "$LAST" "$ID" >> database
fi
printf "Would you like to search for an employee? y/n \n"
read -r SEARCH
if [ "$(tr '[:upper:]' '[:lower:]' <<<"$SEARCH")" = "y" ]
then
printf "Enter the first name, last name or employee ID to search for. : \c"
read -r WORD
grep "$WORD" database
fi
Notes on refactoring/repair:
Do not rely on echo -e in most cases printf works better and looks more like coding,
use read -rto mot mangle backslashes on input,
quote variables from input (with real ASCII quote characters), as the shell parser otherwise does funny things,
do not test against y and Y but simply lowercase the string received to only compare one variant.
Use some indent concept to track, and
use a shell linter as suggested by a commenter already (that one works nicely currently).
The above code does have no errors indicated in the above mentioned linter.
Small task for as exercise for the reader (thanks andlrc :)
Use lowercase variable names and I amend meaningful names
Enjoy the learning of the shell coding!

Bash Script: want to call a function that reads input

I'm writing a script that calls on a function that reads for input in multiple lines. I want to pass parameters into the read, but I don't know if I can or how to.
aka how to get enter-grades to take my values as input instead of waiting for input at the prompts?
Inside my bash script
...
login="studentName"
echo "enter score:"
read score
echo "comments:"
read comments
enter-grades $hw #---> calls another function (dont know definition)
#
# i want to pass parameters into enter-grades for each read
echo "$login" #---> input to enter-grade's first read
echo "$score $comments" #---> input to enter-grade's second read
echo "." #---> input to enter-grade's third read
outside my bash script
#calling enter-grades
> enter-grades hw2
Entering grades for assignment hw2.
Reading previous scores for hw2...
Done.
Enter grades one at a time. End with a login of '.'
Login: [READS INPUT HERE]
Grade and comments: [READS INPUT HERE]
Login: [READS INPUT HERE]
Assuming that enter-grades does not read directly from the terminal, just supply the information on that program's standard input:
login="studentName"
read -p "enter score: " score
read -p "comments: " comments
then, group your echo commands together, and pass all that into the program:
{
echo "$login"
echo "$score $comments"
echo "."
} | enter-grades "$hw"
or, succinctly
printf "%s\n" "$login" "$score $comments" "." | enter-grades "$hw"
Quote all your variables.
Or, with a here-doc
enter-grades "$hw" <<END
$login
$score $comments
.
END

How to loop script till user input is empty?

I am trying to make my script to repeat till the user leaves the block question empty. I just got the loop to run, but I can not find a way to make it possible to stop it when block is empty.
I hope some one can help me!!
#!/bin/tcsh -f
#
set word="start"
until ($word !=""); do
#First ask for Compound and Block Name.
echo -n "please enter block name: "
read block
echo -n "please enter compound name: "
read compound
#Now coping template with new name
#
cp Template $block
#
for line in `cat $block`;do
echo $line | sed -e "s/test1/${block}/g" -e "s/test2/${compound}/g" >>./tmp124.txt
done
mv ./tmp124.txt $block
done
Do you want to use bash or csh? You are using bash syntax but tagged your question csh and call tcsh in the first line of your code.
To answer your question, here are examples of how to iterate on standard input until some input is empty:
For tcsh:
#!/bin/tcsh
while ( 1 )
set word = "$<"
if ( "$word" == "" ) then
break
endif
# rest of code...
end
For bash:
#!/bin/bash
while read word; do
if [ -z $word ]; then
break
fi
# rest of code...
done
Use "Until do" loop,
Eg :
For session variable i am assigning default value, Then entering loop. User can pass any value on each prompt when the value is empty, Loop will Terminate and exit the script.
session="Mysession"
until [$session -eq $null]
do
echo $session
echo "Leave Blank to Terminate session"
read -p "Enter session name : " session
done
echo "Exiting.."

sed with loop to replace certain fields in a file with delimiter :

How should I use the sed command to replace certain fields with delimiter : and run a check to make sure that the user's input can be found within the file & if it can't be found it will loop again.
main_menu #function main_menu
echo "1) choice 1"
echo "2) choice 2"
read choice #read user choice on which choice he wants
if [ $choice -eq 1 ]
then
edit_item #function
read $choice_e #read input
grep -iqs "$choice_e: " Item.txt && echo "item found" #search file to find match
while [[ ! ${choice_e} =~ ^([Item.txt])$ ]]; do #loop to find if input matches search
echo "New Title: " #input new
read choice_n
sed -i 's/^/"$choice_n"\t/' Item.txt #edit the item
done
edit_item
else
echo "error" #return user to input again
fi
The invocation of sed is flawed because of the single quotes mixed with double quotes:
sed -i 's/^/"$choice_n"\t/'
The single quotes mean that the $ (and double quotes) are not interpreted by the shell. What you're probably after is:
sed -i "s/^/$choice_n\t/"
Without knowing exactly which shell and version of sed you're using, it isn't clear whether the \t sequence will be translated to a tab or not. In Bash, you could use the ANSI C Quoting mechanism:
sed -i "s/^/$choice_n"$'\t'/
I don't see where your 'delimiter :' is coming into play at all.

Resources