LoginSignup
109
89

More than 5 years have passed since last update.

シェルスクリプトでパスワード入力プロンプト

Last updated at Posted at 2013-11-21

ユーザーにパスワードを入力してもらうシェルスクリプトを作成していたら
bash の read コマンドに便利なオプションがあったのでメモ。

入力プロンプトに "Password:" と表示するには -p が使えます。
入力元が端末のときのみプロンプトを表示するという賢いオプションです。

         -p prompt
                Display prompt on standard error, without a trailing new-
                line, before attempting to read any input.  The prompt is
                displayed only if input is coming from a terminal.

入力した文字を画面に表示しないようにするには -s が使えます。

         -s     Silent mode.  If input is coming from a terminal, charac-
                ters are not echoed.

以上を踏まえてスクリプトを書いてみました。

readpw1.sh
#!/bin/bash
read -sp "Password: " pass
echo "<<$pass>>"

実行してみましょう。端末と echo から "hogehoge" を入力してみます。

$ ./readpw1.sh
Password: <<hogehoge>>
$ echo hogehoge | ./readpw.sh
<<hogehoge>>

キーボードから入力した Enter は read が奪ってしまい表示が改行されません。
では read のあとに echo してみましょう。

readpw2.sh
#!/bin/bash
read -sp "Password: " pass
echo
echo "<<$pass>>"

実行してみます。

$ ./readpw2.sh 
Password: 
<<hogehoge>>
$ echo hogehoge | ./readpw.sh 

<<hogehoge>>

今度は echo で入力したときに無駄な空行が出力されてしまいました。

入力元が端末かどうか調べるには tty を使います。

readpw3.sh
#!/bin/bash
read -sp "Password: " pass
tty -s && echo
echo "<<$pass>>"

実行してみましょう。

$ ./readpw3.sh 
Password: 
<<hogehoge>>
$ echo hogehoge | ./readpw.sh
<<hogehoge>>

いい感じです。

109
89
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
109
89