함수 confirm()

confirm()
yes/no prompt
Are you sure you want to do this? [y/N]

1 Bash[ | ]

read -r -p "Are you sure you want to do this? [y/N] " response
case $response in
    [yY][eE][sS]|[yY]) 
        do_something
        ;;
    *)
        do_something_else
        ;;
esac
read -r -p "Are you sure you want to do this? [y/N] " response
if [ `echo $response | grep -ciP "^\s*y(es)*\s*$"` -ne 0 ]; then
        echo yes
else
        echo no
fi

2 Go[ | ]

package main

import (
	"fmt"
	"log"
	"regexp"
)

func confirm() bool {
	var response string
	_, err := fmt.Scanln(&response)
	if err != nil {
		log.Fatal(err)
	}
	match, _ := regexp.MatchString("[yY][eE][sS]|[yY]", response)
	return match
}

func main() {
	fmt.Print("Are you sure you want to do this? [y/N] ")
	isYes := confirm()
	fmt.Println("isYes=", isYes)
}

3 Java[ | ]

import java.util.Scanner;

public class Confirm {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Are you sure you want to do this? [y/N] ");
		String text = scanner.nextLine();
		Boolean result = checkConfirm(text);
		System.out.println("Is yes : " + result);
	}
	
	static Boolean checkConfirm(String text) {
		return text.matches("[yY][eE][sS]|[yY]");
	}
}

4 JavaScript[ | ]

if ( confirm("Press a button!") ) {
    console.log("You pressed OK!");
} else {
    console.log("You pressed Cancel!");
}

5 PHP[ | ]

echo "Are you sure you want to do this? [y/N] ";
$response = strtoupper(trim(fgets(STDIN)));
if ( $response != 'Y' && $response != 'YES' ) {
	echo "NOT yes...\n";
}
else {
	echo "Yes!!!\n";
}

6 Windows Batch[ | ]

윈도우 비스타 이후 문법으로서, 윈도우 XP에서는 지원하지 않는다.

@echo off
CHOICE /M "Are you sure"
IF %ERRORLEVEL% == 1 echo Yes
IF %ERRORLEVEL% == 2 echo No

모든 윈도우 NT 계열의 호환성을 위해서는 다음과 같이 처리할 수 있다.

@echo off
set /p YN="Are you sure [Y/N]?"
IF "%YN%" == "Y" echo YES
IF "%YN%" == "N" echo NO

7 DOS Batch[ | ]

MS-DOS 6.22까지의 문법이다.

@echo off
CHOICE Are you sure
IF ERRORLEVEL 1 echo YES
IF ERRORLEVEL 2 echo NO

8 같이 보기[ | ]

9 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}