Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Bash: Assign the output of a command to an array element?

  • 24-10-2013 10:53PM
    #1
    Closed Accounts Posts: 4,763 ✭✭✭


    I am writing a script where I interactively receive input from the user. I'd ideally like to read the answers into an array. Code in question:
        for q in $(seq 0 ${#img_question[@]}); do
            until [[ $[img_answer[$q]} == '^[0-9]+([.][0-9]+)?$' ]]; do
                echo -ne ${img_question[$q]}
                read ${img_answer[$q]}
            done
        done
    

    I'm taking in straight numerical values. The thing is, values recorded by the array element are null, empty. I've worked through a few permutations of this, but nothing seems to work. I've tried to indirectly assign to the array element through an intermediary variable, but it is treated as a command. Example:
    [me][~] # read ans
    Testing
    [me][~] # echo $ans
    Testing
    [me][~] # {test_array[0]}=$ans
    -bash: {test_array[0]}=Testing: command not found
    

    What's the best way (if any) to accomplish this?


Comments

  • Moderators, Arts Moderators Posts: 36,204 Mod ✭✭✭✭pickarooney


    In the second part, should you use a 'let' for the assignment of the $ans variable to the first slot in the array?


  • Closed Accounts Posts: 4,763 ✭✭✭Fenster


    I think I might have it now. Your suggestion was wrong, but it starkly illuminated my mistake. :)


  • Moderators, Arts Moderators Posts: 36,204 Mod ✭✭✭✭pickarooney


    Glad to be the blacklight :D


  • Closed Accounts Posts: 4,763 ✭✭✭Fenster


    I was using completely the wrong syntax:
            until [[ $img_answer[$q] == $is_valid ]]; do
                echo -ne ${img_question[$q]}
                read img_answer[$q]
                # Validation
            done
    

    I was simultaneously trying to call the variable, and assign to it, which Bash couldn't handle.


Advertisement