A process that displays [y / n]
and prompts confirmation and target instructions, which is often used when creating a small CLI tool. There are three ways to do that: Go, Python, and bash.
What you are doing
If you ask ʻare you okay? and answer only No (n), it will display ʻoh no.
, otherwise it will display yeah good.
.
--Display message
--Input from standard input to line feed (Enter)
--Front and rear space trim
--Discrimination
bash
#!/bin/bash
read -p "are you okay?[Y/n]" ans
if [ "$ans" = "n" ]; then
echo "oh no."
else
echo "yeah good."
fi
Use read
, simply read it, and then write the processing for it. read
splits it with whitespace and stores it in ans. At that time, the front and rear white spaces have been removed.
Python
from sys import stdin
print "are you okay?[Y/n]"
ans = stdin.readline()
if ans.strip() == "n":
print "oh no."
else:
print "yeah good."
It's almost the same as bash, except that the string read by readline ()
contains a newline at the end.
This time it is removed together with strip ()
, but if not, use only the end with rstrip ()
etc.
If you compare the character strings as they are, the line breaks will not match, resulting in unintended movement.
Go
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println("are you okay?[Y/n]")
reader := bufio.NewReader(os.Stdin)
ans, err := reader.ReadString('\n')
if err != nil {
fmt.Print("input err:", err)
os.Exit(1)
}
if strings.TrimSpace(ans) == "n" {
fmt.Println("oh no.")
} else {
fmt.Println("yeah good.")
}
}
As expected, it will be longer than bash and Python because you write main and error handling. Like Python, Go also includes line breaks, so delete it appropriately with strings.TrimSpace ()
or strings.TrimRight ()
.
Recommended Posts