Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script, read on same line after echoing a message

Tags:

linux

bash

shell

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.

like image 814
user1263746 Avatar asked Mar 15 '12 12:03

user1263746


People also ask

How do I print echo on the same line?

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.

How do you echo without a new line?

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.

How do you take a single line of input from the user in a shell script?

You need to use read command in a shell script to read single line of input frm the user in a shell.

What is $@ and $* in shell script?

"$@" 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.


4 Answers

Solution: read -p "Enter [y/n] : " opt

From help read:

  -p prompt output the string PROMPT without a trailing newline before
        attempting to read
like image 123
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 23:10

Ignacio Vazquez-Abrams


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.)

like image 29
TaylanKammer Avatar answered Oct 18 '22 22:10

TaylanKammer


echo -n "Enter [y/n] : " ; read opt

OR! (Later is better)

read -p "[y/n]: " opt
like image 13
heldt Avatar answered Oct 18 '22 23:10

heldt


use -n handle in echo, that will avoid trailing newline

echo -n "Enter [y/n] : "
read opt
like image 4
Fazly Avatar answered Oct 18 '22 22:10

Fazly