Y / n processing in bash, python and Go

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

Y / n processing in bash, python and Go
Multithreaded processing in python
Implemented memoization recursion and exploration in Python and Go
Text processing in Python
Queue processing in Python
Full-width and half-width processing of CSV data in Python
Summary of date processing in Python (datetime and dateutil)
Asynchronous processing (threading) in python
Stack and Queue in Python
Image Processing Collection in Python
Unittest and CI in Python
Using Python mode in Processing
Signal processing in Python (1): Fourier transform
MIDI packages in Python midi and pretty_midi
Difference between == and is in python
View photos in Python and html
Sorting algorithm and implementation in Python
100 Language Processing Knock Chapter 1 in Python
Manipulate files and folders in Python
About dtypes in Python and Cython
Check and move directories in Python
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
cout << "Hello, World! \ N" in python
Function synthesis and application in Python
Export and output files in Python
python string processing map and lambda
Reverse Hiragana and Katakana in Python2.7
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
Create and read messagepacks in Python
processing to use notMNIST data in Python (and tried to classify it)
Overlapping regular expressions in Python and Java
In Python 3.8, pow (n, -1, 1000000007) looks better than pow (n, 1000000007-2, 1000000007)
Differences in authenticity between Python and JavaScript
Modules and packages in Python are "namespaces"
Avoid nested loops in PHP and Python
Python and Bash on Cisco Catalyst IOS-XE
Socket communication and multi-thread processing by Python
AM modulation and demodulation in Python Part 2
Implement and understand union-find trees in Go
difference between statements (statements) and expressions (expressions) in Python
Eigenvalues and eigenvectors: Linear algebra in Python <7>
Implementation module "deque" in queue and Python
Line graphs and scale lines in python
Implement FIR filters in Python and C
Differences in syntax between Python and Java
Check and receive Serial port in Python (Port check)
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Search and play YouTube videos in Python
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Write O_SYNC file in C and Python
Dealing with "years and months" in Python
Extract every n elements from an array (list) in Python and Ruby
Read and write JSON files in Python
Easily graph data in shell and Python
Find and check inverse matrix in Python
Linear Independence and Basis: Linear Algebra in Python <6>
Call sudo in Python and autofill password