petabyte
petabyte

Reputation: 1567

How to get user input right when running a shell script?

For example, if i have a shell program "shell1" and run "./shell1 hello world", how can I store the hello world in a variable? If I try to use read, it only accepts user input after I run ./shell1 first.

Upvotes: 0

Views: 225

Answers (1)

dogbane
dogbane

Reputation: 274828

You are referring to parameters being passed to the script.

To capture them use $1 for the first parameter, $2 for the second, $3 for the third, and so forth. Use "$@" to capture all parameters into a single variable.

For example, try adding the following to your script:

param1="$1"
param2="$2"
echo "Param1 is $param1, Param2 is $param2"

allParams="$@"
echo "All params are: $allParams"

Take a look at Advanced Bash-Scripting Guide: Positional Parameters for more information.

Upvotes: 2

Related Questions