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.
CodePudding user response:
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 read
s 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.
Edit. For fun, I include here the other solutions I wrote in comments, since you are not specially requiring here-strings.
(echo "$username" ; echo "$password") | ./input.sh
{echo "$username" ; echo "$password" ; } | ./input.sh
printf "%s\n" "$username" "$password" | ./input.sh
./input.sh < <(echo "$username" "$password")
./input.sh < <(printf "%s\n" "$username" "$password")
Plus of course solutions that changes ./input.sh
#!bin/bash
username="$1"
password="$2"
echo "The Current User Name is $username"
echo " The Password is $password"
called with ./input "$username" "$password"
Or
#!bin/bash
echo "The Current User Name is $username"
echo " The Password is $password"
called with username="$username" password="$password" ./input.sh
CodePudding user response:
Easiest way would be something like that:
#!/bin/bash
echo "The Current User Name is $1"
echo "The Password is $2"
$1 represents the first given argument and $2 the second.
[user@vm ~]$ input.sh "user" "password"
Inside the quotation marks ("") put the argument you want to pass.
For more professional/robust solution check this out: Redhat: Bash Script Options/Arguments