Following the shell script that I am executing
#!/bin/sh
echo "Enter [y/n] : "
read opt
Its output is
Enter [y/n] :
Y
I want that the variable should be read on the same line like below
Enter [y/n] : Y
Should be simple I guess, but I am new to bash scripting.
The 2 options are -n and -e . -n will not output the trailing newline. So that saves me from going to a new line each time I echo something. -e will allow me to interpret backslash escape symbols.
The best way to remove the new line is to add '-n'. This signals not to add a new line. When you want to write more complicated commands or sort everything in a single line, you should use the '-n' option. So, it won't print the numbers on the same line.
You need to use read command in a shell script to read single line of input frm the user in a shell.
"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). So basically, $# is a number of arguments given when your script was executed. $* is a string containing all arguments. For example, $1 is the first argument and so on.
Solution: read -p "Enter [y/n] : " opt
From help read
:
-p prompt output the string PROMPT without a trailing newline before
attempting to read
The shebang #!/bin/sh
means you're writing code for either the historical Bourne shell (still found on some systems like Solaris I think), or more likely, the standard shell language as defined by POSIX. This means that read -p
and echo -n
are both unreliable.
The standard/portable solution is:
printf 'Enter [y/n] : '
read -r opt
(The -r
prevents the special treatment of \
, since read
normally accepts that as a line-continuation when it's at the end of a line.)
If you know that your script will be run on systems that have Bash, you can change the shebang to #!/bin/bash
(or #!/usr/bin/env bash
) and use all the fancy Bash features. (Many systems have /bin/sh
symlinked to bash
so it works either way, but relying on that is bad practice, and bash
actually disables some of its own features when executed under the name sh
.)
echo -n "Enter [y/n] : " ; read opt
OR! (Later is better)
read -p "[y/n]: " opt
use -n handle in echo, that will avoid trailing newline
echo -n "Enter [y/n] : "
read opt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With