How do I read a value from user input into a variable
Asked Answered
B

3

10

In ksh, how do I prompt a user to enter a value, and load that value into a variable within the script?

command line

echo Please enter your name: 

within the script

$myName = ?
Boling answered 23/7, 2011 at 19:40 Comment(0)
F
20

You want read:

echo Please enter your name:
read name
echo $name

See read(1) for more.

Footy answered 23/7, 2011 at 19:51 Comment(0)
C
8

You can do it in a single line, like so:

read -p "Please enter your name:" myName

To use variable in script

echo "The name you inputed is: $myName"
echo $myName
Chloras answered 15/2, 2016 at 0:47 Comment(4)
this works well on cygwin, but not for ksh on AIX 7.1 - accepted answer from Marcus works on bothRumpus
The question has a linux tag, so I'm assuming the OP wants a Linux answer. AIX, a proprietary branch of Unix deved by IBM is not part of Linux. As far as I know this has worked on all the branches of Linux I've worked with and it has the formatting advantage that the first answer doesn't (as using an echo followed by a read statement forces uses input on a new line whereas read -p does not).Chloras
NOTE: -p is not POSIXJodoin
ksh does not support read -p (or rather, the -p option to read does something different in ksh). This question is clearly tagged ksh and it is reinforced in the question text, but you still provided a Bash answer.Housing
H
0

ksh allows you to specify a prompt as part of the read command using this syntax:

read myName?"Please provide your name: "
Housing answered 4/6, 2021 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.