概要
シェルスクリプトでパスワードをプロンプトから入力させる方法について記載します。
目的
シェルスクリプトで繰り返しパスワードの必要なコマンドを実行するためにパスワードをプロンプトで入力させたいです。
コード
read
で読み込むことができます。-p
オプションでプロンプトを出して、-s
オプションで入力した文字を表示しないようにしています。
get_password.sh#!/bin/bash read -rsp 'Password: ' password cat <<EOF password = ${password} EOF
以下、利用したオプションのmanページです。
readコマンドのオプションの説明$ man bash ... read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...] One line is read from the standard input, or from the file descrip- tor fd supplied as an argument to the -u option, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in IFS are used to split the line into words. The backslash character (\) may be used to remove any spe- cial meaning for the next character read and for line continuation. Options, if supplied, have the following meanings: ... -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. -r Backslash does not act as an escape character. The back- slash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continua- tion. -s Silent mode. If input is coming from a terminal, characters are not echoed.
動作確認
エコーバックされずに入力できていることが確認できました。