0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Linux】readコマンドのpオプションはシェルによって挙動が異なる

Posted at

Bashの場合

以下のようにすることで入力を要求する際にメッセージを表示できる。

$ read -p 'What is your project named? > ' PROJECT_NAME
What is your project named? > 
  • Bashのread

Zshの場合

Zshで上記と同じコマンドを実行すると以下のようにエラーとなる。

$ read -p 'What is your project named? > ' PROJECT_NAME
zsh:read:1: -p: no coprocess

これはpオプションの挙動が異なることから生じている。

  • Zshのread

解決策

ZshでBashと同様のことを実現するには以下のように記述する。

$ read PROJECT_NAME'?What is your project named? > '
What is your project named? > 

またZshとBash両方で動作させるには以下のようにする。

  • 条件分岐
if [ -n "$ZSH_VERSION" ]; then
  read PROJECT_NAME'?What is your project named? > '
else
  read -p 'What is your project named? > ' PROJECT_NAME
fi

echo $PROJECT_NAME
if [[ $ZSH_EVAL_CONTEXT = toplevel ]]; then
  read PROJECT_NAME'?What is your project named? > '
else
  read -p 'What is your project named? > ' PROJECT_NAME
fi

echo $PROJECT_NAME
  • 別のコマンドでプロンプトを出力
echo -n 'What is your project named? > '
read PROJECT_NAME
echo $PROJECT_NAME
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?