LoginSignup
7
1

More than 3 years have passed since last update.

やりたいこと

bashで配列の中身をランダムに抽出したい!
これってトリビアのタネになりませんか?

やり方

bashでは${#ARRAY[*]}で配列のサイズが取得できる。

random_array.sh
#!/bin/bash
readonly ARRAY=("foo" "bar" "baz" "qux" "quux" "corge")
echo ${#ARRAY[*]}      # 6
echo ${#ARRAY[@]}      # 6 @でも取得できるらしい。

次にランダムな値ですが、bashではRANDOMという謎の変数が用意されているらしい。
0〜32767までが範囲になっている。

random_array.sh
#!/bin/bash
echo $RANDOM           # 14067
echo $RANDOM           # 31125 値がランダムに取れている。
echo $(($RANDOM%10))   # 3     0〜9までの10パターンが取得できる。

これを組み合わせて使えば、配列からランダムな値が取得できる!

random_array.sh
#!/bin/bash
readonly ARRAY=("foo" "bar" "baz" "qux" "quux" "corge")
echo ${ARRAY[$(($RANDOM % ${#ARRAY[*]}))]} # foo
7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1