0

I have to pick a random data in several arrays. So I made a function that takes over the array and returns a random value.

This is my code,

./pick_data.sh

pick_random_data()
{
    # seed random generator
    RANDOM=$$$(date +%s)

    #take array as parameter
    declare -a argArr="${!1}"

    # pick a random entry from the domain list to check against
    randomResult=${argArr[$RANDOM % ${#argArr[@]}]}

    echo "$randomResult"    
}


main()
{

    local user_agent=(
        "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8"
        "INI_Ibis"
        "tving/5.2.6.4720 CFNetwork/893.14.2 Darwin/17.3.0"
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063"
        )

    result=pick_random_data user_agent[@]

    echo $result
}

main

error is

test.sh: line 27: user_agent[@]: command not found

I refer these posts,

Passing arrays as parameters in bash

https://www.christianroessler.net/tech/2015/bash-array-random-element.html

I don't know what I missing.

YEEN
  • 67
  • 1
  • 5
  • 1
    You are not using command substitution: `result=$(...)`. Possible duplicate of [How to set a variable to the output from a command in Bash?](https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash). – PesaThe Jan 18 '18 at 02:12
  • 1
    BTW, `argArr="${!1}"` is a string assignment. You need to use an array: `argArr=("${!1}")`. – PesaThe Jan 18 '18 at 02:24
  • @PesaThe "(${!1})" is in my code before, but `( )` occurred error. So I removed them. And I add the result=$(...), then it's work! Thanks. But I have some problem yet. Function return just first value that `"Mozilla/5.0 ... like Gecko"`. – YEEN Jan 18 '18 at 02:30
  • The quotes should be like this: `argArr=("${!1}")`. Changing that and using `$(...)` makes your code work for me. – PesaThe Jan 18 '18 at 02:33
  • Oh, sorry. Never mind what I am saying above. It's a mistake. I got another problem that function doesn't pass the value and just print all of in array values. – YEEN Jan 18 '18 at 02:36
  • 1
    Oh, I just see your comment now. And it's working perfectly. Thank you so much! – YEEN Jan 18 '18 at 02:37
  • If you write the answer, I will vote you. :) – YEEN Jan 18 '18 at 02:48

0 Answers0