printfでread -sを使用する方法

printfでread -sを使用する方法

「read -s」を使用すると、既存の行が削除され、次のような行に次のプロンプトが表示されます。このエラーの解決策を教えてください。画面にパスワードを表示するのではなく、「-s」を使用して読む必要があります。

スクリプト:


$ cat a.sh
printf "Enter the db name : "
read -r sourcedb
printf "Enter the source db username: "
read -r sourceuser
printf "Enter the source database password: "
read -s sourcepwd;
printf "Enter the target database username: "
read -r targetuser

現在の出力:


$ ./a.sh
Enter the db name : ora
Enter the db username: system
Enter the db password: Enter the target database username:

希望の出力:


$ ./a.sh
Enter the db name : ora
Enter the db username: system
Enter the db password: 
Enter the target database username:

私はLinuxを使用しています。

ベストアンサー1

-sreadこのユーティリティの標準オプションではありません。 ksh ではシェル履歴に入力を保存し、bash と zsh では端末エコーを抑制します。他のほとんどのシェルではこれは無効なオプションであるため、使用するには-sshe-bangを指定して誤解を招く拡張名を変更する必要があります。.sh

端末を抑制するechoということは、押されたときにエコーされるCRとNLEnterも抑制されるという意味なので、手動で送信する必要があります。次のプロンプトの前に改行文字を印刷します(ターミナルドライバはこれをCR + NLに変更します)。

プロンプトは、スクリプト生成出力用に予約する必要があるstdoutではなくstderrにも移動する必要があります。

#!/bin/bash -
printf>&2 "Enter the db name: "
read -r sourcedb
printf>&2 "Enter the source db username: "
read -r sourceuser
printf>&2 "Enter the source database password: "
IFS= read -rs sourcepwd
printf>&2 "\nEnter the target database username: "
read -r targetuser

組み込みread機能(エコー抑制をサポートするシェル)はプロンプトの自己放出をサポートします(stderrに送信されます)。そして:bashzsh-szsh

read 'var?prompt'

kshとbashのように:

read -p prompt var

printfしたがって、以下を使用する代わりに:

#!/bin/bash -
read -rp 'Enter the db name: ' sourcedb
read -rp 'Enter the source db username: ' sourceuser
IFS= read -rsp 'Enter the source database password: ' sourcepwd
read -rp $'\nEnter the target database username: ' targetuser

おすすめ記事