How to readLine silently

In a command line app, I'd like to input the username and password.
But I'd like to hide the '123456' because its a password.

In bash I can use

read -s

And what's the Swifty way?

Below is the implementation of getInput.

func getInput() -> String {
// 1
let keyboard = FileHandle.standardInput
// 2
let inputData = keyboard.availableData
// 3
let strData = String(data: inputData, encoding: String.Encoding.utf8)!
// 4
return strData.trimmingCharacters(in: CharacterSet.newlines)
}

Hello @PhilCai, and welcome to the Swift Forums!

Unfortunately, as far as I’m aware, what you’re trying to do has no portable solution. On Linux, you should be able to use getpass, and on most Unices you can use the functions found in <termios.h>, namely tcsetattr(3), to turn off echoing. If third-party libraries are an option, you may want to take a look at curses, which can provide this functionality.

2 Likes

:laughing:Wow, thanks a lot @saagarjha . It seems curses is what I want.

On Linux, you should be able to use getpass …

FYI, getpass exists on macOS as well.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"

1 Like

Thanks @eskimo . But it will be great if there is a func readline(silent: Bool)

Here you go:

func readline(silent: Bool) -> String? {
    return silent ? String(cString: getpass("")) : readLine()
}

:joy:Good idea