创建一个本质上充当算命先生或"magic 8 ball"的 bash 脚本



我正在尝试创建一个本质上像一个具有 6 种不同响应(是、否、也许、难以分辨、不太可能和未知)的魔术 8 球的 bash 脚本。关键是,一旦给出答复,就不应该再次作出答复,直到给出所有答复为止。

这是我到目前为止所拥有的:

#!/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

基本上,我将 6 个响应全部放在临时文件的不同行上,我正在尝试构建循环,以便一旦给出响应,它就会创建一个没有该响应的新文件 (temp2),然后将其复制回 temp。然后,一旦临时文件为空,它将从头开始继续。

我很肯定我当前的内循环是错误的,我需要一个外循环,但我对此相当陌生,我被卡住了。

任何帮助将不胜感激。

尝试这样的事情:

#!/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

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

#!/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
$ 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.

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

最新更新