How to pass multiple variables as input in shell script in non-interactive way

I am trying to make this interactive script take inputs in a non-interactive way by declaring $username and $password variables in bash env and pass them as inputs to the script. By running ./input.sh <<< "$username"

#!bin/bash
read username
read password
echo "The Current User Name is $username"
echo " The  Password is $password"  

is there a way to pass both the variables as input? Because with what I have tried it only takes one input this way.

>Solution :

So, staying as close as possible as your initial try (but I doubt that is the best solution for any real problem), what you are asking is "how I can pass 2 lines with here-string".

A possible answer would be

./input.sh <<< "$username"$'\n'"$password"

here-strings are the construct you are using when using <<<. When you type ./input.sh <<< astring it is, sort-of, the same as if you were typing echo astring | ./input.sh: it use the string as standard input of ./input.sh. Since your reads read lines, you need 2 lines as standard input to achieve what you want. You could have done this that way: (echo "$username" ; echo "$password") | ./input.sh. Or anyway that produces 2 lines, one with $username one with $password and redirecting those 2 lines as standard input of ./input.sh

But with here-string, you can’t just split in lines… Unless you introduce explicitly a carriage return (\n in c notation) in your input string. Which I do here using $'...' notations, that allows c escaping.

Leave a Reply