In bash, there is a builtin called read
which has the -p switch. For example:
read -p "Please enter a value: " value
echo "${value}"
If this file is then executed like $ ./bashfile > result.txt
You will end up with a file containing $value
, but NOT Please enter a value: $value
In go, you can do something similar. Here's a section of code:
fmt.Print("Please enter a value: ")
reader := bufio.NewReader(os.Stdin)
value, _ := reader.ReadString('
')
fmt.Println(value)
If you were to run that with $ ./goexecutable > result.txt
The content of result.txt will look like Please enter a value: value
Is there an equivalent in go to the bash <PROMPT>
string from read -p which prints to the command line, but not to stdout?
Bash's read -p
just prints the prompt to stderr
. You can tell by redirecting the stderr of your script to /dev/null
and noticing that no prompt prints.
./bashfile > result.txt 2> /dev/null
You can do the same in Go using fmt.Fprintf
.
fmt.Fprintf(os.Stderr, "Please enter a value: ")