Search code examples
macosbashcommandargumentsprompt

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.


Solution

  • 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.