pietz
pietz

Reputation: 2533

Prompt for user input in bash script and read it like command line arguments?

I'm working on a bash script (exclusively used on OS X) that the user executes by double clicking the file. I replaced the .sh ending with .command so its natively opened by the terminal, after which a small description text tells the user what to do. The script waits for an input, which i would love to handle just like command line arguments. Giving me the possibility to access the single "words" with $1, $2, $3, ... and using the "shift" command inside the script.

I found out that the "read" command can save an input to a variable, but accessing the default variable $REPLY will give me the entire input as a string. Using the code

read var1 var2 var3

gets me one step closer by splitting the input like i want but only for a fixed number of variables (in this case 3). In theory, the user input can be a hundred arguments or more, which is why it feels stupid to create so many variables. I could also parse the default $REPLY variable and separate it by spaces, but i feel like there must be an easier way to handle user input just like command line arguments.

Thank you for your time.

Upvotes: 1

Views: 3494

Answers (2)

rich remer
rich remer

Reputation: 3577

This will not handle quotes, but should otherwise work:

doStuff() {
    echo first of $# args is $1
}

read VARS
doStuff $VARS

This works because variable expansion takes place on $VARS before calling doStuff, and the expanded command will be something like doStuff foo bar baz 42 23 fin.

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74596

In bash, one option would be to use the -a switch to read the input into an array:

read -ra args

Then you can access each argument like "${args[0]}", "${args[1]}", etc.

I've also used the -r switch as it handles input that contains backslashes in a more sensible way (i.e. it doesn't try to do anything clever for you, it just leaves the strings as they are).

If you wanted to handle each argument one by one, another option would be to use a loop:

while read -r arg
do
    # whatever with each argument
done

The loop would continue, processing one argument at a time, until the user entered a Ctrl-d.

Upvotes: 2

Related Questions