创建一个充当算命先生或“魔术8球”的bash脚本

时间:2012-12-15 02:23:30

标签: bash loops scripting

我正在尝试创建一个bash脚本,它基本上就像一个魔术8球,有6种不同的响应(是,否,可能,很难说,不太可能和未知)。关键是一旦给出答复,在给出所有答复之前不应再给出答案。

这是我到目前为止所做的:

#!/bin/bash
echo "Ask and you shall receive your fortune: "
n=$((RANDOM*6/32767))
while [`grep $n temp | wc awk '{print$3}'` -eq 0]; do
   n=$((RANDOM*6/32767))
done
grep -v $n temp > temp2
mv temp2 temp

基本上我在temp文件的不同行上都有6个响应,我试图构造循环,这样一旦给出响应,它就会创建一个没有响应的新文件(temp2),然后将其复制回来温度然后,一旦临时文件为空,它将从头开始。

我非常肯定我当前的内循环是错误的,而且我需要一个外循环,但我对此很新,我被卡住了。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

#!/bin/bash

shuffle() {
   local i tmp size max rand

   # $RANDOM % (i+1) is biased because of the limited range of $RANDOM
   # Compensate by using a range which is a multiple of the array size.
   size=${#array[*]}
   max=$(( 32768 / size * size ))

   for ((i=size-1; i>0; i--)); do
      while (( (rand=$RANDOM) >= max )); do :; done
      rand=$(( rand % (i+1) ))
      tmp=${array[i]} array[i]=${array[rand]} array[rand]=$tmp
   done
}

array=( 'Yes' 'No' 'Maybe' 'Hard to tell' 'Unknown' 'Unlikely' )

shuffle
for var in "${array[@]}"
do
  echo -n "Ask a question: "
  read q
  echo "${var}"
done

答案 1 :(得分:1)

我编写了一个遵循初始方法的脚本(使用临时文件):

#!/bin/bash

# Make a copy of temp, so you don't have to recreate the file every time you run this script
TEMP_FILE=$(tempfile)
cp temp $TEMP_FILE

# You know this from start, the file contains 6 possible answers, if need to add more in future, change this for the line count of the file
TOTAL_LINES=6

echo "Ask and you shall receive your fortune: "
# Dummy reading of the char, adds a pause to the script and involves the user interaction
read

# Conversely to what you stated, you don't need an extra loop, with one is enough
# just change the condition to count the line number of the TEMP file 
while [ $TOTAL_LINES -gt 0 ]; do
    # You need to add 1 so the answer ranges from 1 to 6 instead of 0 to 5
    N=$((RANDOM*$TOTAL_LINES/32767 + 1))

    # This prints the answer (grab the first N lines with head then remove anything above the Nth line with tail)
    head -n $N < $TEMP_FILE | tail -n 1

    # Get a new file deleting the $N line and store it in a temp2 file
    TEMP_FILE_2=$(tempfile)
    head -n $(( $N - 1 )) < $TEMP_FILE > $TEMP_FILE_2
    tail -n $(( $TOTAL_LINES - $N )) < $TEMP_FILE >> $TEMP_FILE_2
    mv $TEMP_FILE_2 $TEMP_FILE

    echo "Ask and you shall receive your fortune: " 
    read

    # Get the total lines of TEMP (use cut to delete the file name from the wc output, you only need the number)
    TOTAL_LINES=$(wc -l $TEMP_FILE | cut -d" " -f1)
done

答案 2 :(得分:0)

$ man shuf

SHUF(1)                                                           User Commands

NAME
       shuf - generate random permutations

SYNOPSIS
       shuf [OPTION]... [FILE]
       shuf -e [OPTION]... [ARG]...
       shuf -i LO-HI [OPTION]...

DESCRIPTION
       Write a random permutation of the input lines to standard output.

接下来会有更多内容,您可以在自己的机器上阅读:)