If you know the number of arguments it is easy. Basics first.
#!/bin/bash
if [ $# == 0 ]
then
read v1 # gets onto new line. reads the whole line until ENTER
read v2 # same
read v3 # same
fi
# Parse $v1, $v2, $v3 as needed and run your script
echo ""
echo "Got |$v1|, |$v2|, |$v3|"
When you type automate.sh
and hit enter the script is started, having received no arguments. With no arguments ($# == 0
) the first read
is executed, which prints a new line, waits, and gets the line typed in (once enter is hit) into $v1
. The control goes back to the script, the next read gets the next typed line ... after the last one it drops out of if-else
and continues. Parse your variables and run the script.
Session:
> automate.sh Enter
typed line Enter
more items Enter
yet more Enter
Got |typed line| |more items| |yet more|
>
You don't need Control-Enter
or F5
, it continues after 3 (three) lines.
This also allows you to provide both behaviors. Add an else
, which will be executed if there are some arguments. You can then use the script by either supplying arguments on the first line (invocation you have so far), or in this new way.
If you need an unspecified number of arguments this approach will need more work.
Read words in input line into variables
If read
is followed by variable names, like read v1 v2
, then it reads each word into a variable, and the last variable gets everything that may have remained on the line. So replace read
lines with
read k1 p1 s1
read k2 p2 s2
read k3 p3 s3
Now $k1
contains the first word (from
), and $k2
and $k3
have the first words on their lines; then $p1
(etc) have the second word (:
), and $s1
(etc) have everything else to the end of their lines (a1
, a2
, 'next change'
). So you don't need those single quotes. All this is simple to modify if you want the script to print something on each line before input.
Based on the clarification in the comment, it is indeed desirable to not have to enter the whole strings, as one might think. This is "simple to modify"
read -p 'from :' s1
read -p 'to :' s2
read -p 'msg :' s3
Now the user only needs to enter the part after :
, captured in $s
variables. All else is the same.
See, for example: The section on user input in the Bash Guide; Their Advanced Guide (special variables); For a far more involved user interaction, this post. And, of course, man read
.