问题
I would like bash/terminal command to make it echo
... . . . . . . .. ...... .. . . .
in other words random amounts of dots perhaps 100 dots max, mixed with spaces.
how can this be done via bash script ?
回答1:
Here is a one liner:
max=$((RANDOM%100)); for ((i=0;i<max;i++)); do ((RANDOM%2)) && a="$a." || a="$a "; done; echo "$a"
or in a more readable format:
max=$((RANDOM%100))
for ((i=0;i<max;i++))
do
((RANDOM%2)) && a="$a." || a="$a "
done
echo "$a"
回答2:
If you want the line to be really random, say:
cat /dev/urandom | tr -dc '. ' | fold -w 100 | head -1
For assigning it to a variable, say:
foo=$(cat /dev/urandom | tr -dc '. ' | fold -w 100 | head -1)
A sample output would look like:
...... . . . ....... . ... ..... . ... . . . . . .. .... . . . . ... . .
Simply saying:
cat /dev/urandom | tr -dc '. ' | fold -w 100
would produce endless lines of random data that are 100 characters wide until you interrupt.
回答3:
How about this?
#!/bin/bash
for i in {1..100}; do
even=$(( $RANDOM % 2 ))
if [ $even -eq 0 ]; then
printf " ";
else
printf "."
fi
done
printf "\n"
Or as asked in the comments:
#!/bin/bash
a=$(
for i in {1..100}; do
even=$(( $RANDOM % 2 ))
if [ $even -eq 0 ]; then
printf " ";
else
printf "."
fi
done
printf "\n"
)
echo $a
回答4:
$ x='. '; for i in {1..100}; do printf "${x:$((RANDOM%2)):1}"; done && echo
. .. ... ..... .. . .. . .. . .. . ... ..... . . .. ... . . . .. .. .. .. . .....
That way you can also easily influence the dot-to-space ratio by doing e.g. x='.... ' and using $RANDOM % 5
$ x='.... '; for i in {1..100}; do printf "${x:$((RANDOM%5)):1}"; done && echo
.................. ... ...... . . ..... . ........ . .... ............ ........... .. . ...
or add other characters to your output
$ x='abc '; for i in {1..100}; do printf "${x:$(($RANDOM%4)):1}"; done && echo
b a ccac bb aac abbcccab aa baabb cbbacbacb cbab b a baccccaa bc acc cca ba cacccaaa cbaba ab
来源:https://stackoverflow.com/questions/18483271/how-to-echo-random-amounts-of-dots-mixed-with-spaces