Prompt user from bash command substitution

2019-03-06 23:54发布

I am looking for a one-liner to prompt user for multiple inputs and execute a command using the user inputs as arguments.

The naive approach is:

read -p shirt_size: shirt_size
read -p age: age
the_command some_complicated_arguments $shirt_size $age

Unfortunately it is verbose. Here is a one-liner that behaves the same:

the_command some_complicated_arguments \
  `>&2 printf shirt_size:; head -n 1` `>&2 printf age:; head -n 1`

Unfortunately it is neither compact nor readable. I would like it to be as readable as:

the_command some_complicated_arguments \
  `input shirt_size` `input age`

I would prefer the solution to use bash built-in command or programs usually available on Linux environment.

标签: bash input
1条回答
【Aperson】
2楼-- · 2019-03-07 00:27

Sounds like a homework question to get you to look at functions. If you had a function like:

input() { read -p "$1:" user_input; echo "$user_input"; }

Then your line:

the_command some_complicated_arguments "$(input shirt_size)" "$(input age)"

Would prompt and print the complete line. Although this does nothing to check for valid input or no input.

查看更多
登录 后发表回答