改善bash中的睡眠排序

Pur*_*ret 2 sorting bash

我偶然发现了这个漂亮的bash脚本,这是一个小小的borked.

#!/bin/bash
function f() {
    sleep "$1"
    echo "$1"
}
while [ -n "$1" ]
do
    f "$1" &
    shift
done
wait
Run Code Online (Sandbox Code Playgroud)

它会按照数字给出的秒数休眠,然后输出该数字.最低数字首先唤醒.

我认为可以通过首先将数字除以列表中的最大数字,然后运行它,然后乘以出口时的最大值来改进.

这是我的第一次尝试:

#!/bin/bash

declare -a to_sort

function f() {
    sleep "$1"
    final_var=$(echo "$1*$2"|bc)
    echo "$1"
}
function max(){
for var in "$@"
do
    if [ "$var" -gt "$max" ] # Using the test condition
    then
        max="$var"
    fi
done
}

echo "$1"| read -a to_sort

let max_var = max to_sort

for i in "${to_sort[@]}"
do
    parsed_var=$(echo "$i/$max_var"|bc)
    f parsed_var max_var &
    shift
done
wait
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

tha*_*guy 6

语法和逻辑中存在7个问题,导致无法正常工作,如下所述.

#!/bin/bash

declare -a to_sort

function f() {
    sleep "$1"
    final_var=$(echo "$1*$2"|bc)
    #Output result after multiplication
    #and skip decimals
    echo "${final_var%.*}"
}
function max(){
# Initialize max so we have something to compare against
max=$1
for var in "$@"
do
    if [ "$var" -gt "$max" ]
    then
        max="$var"
    fi
done
# output the max we found
echo $max
}

# Avoid assigning in subshells
read -a to_sort <<< "$1"
#This is how you assign the output of a command
max_var=$(max "${to_sort[@]}")

for i in "${to_sort[@]}"
do
    # Add scale to avoid truncating all to 0
    parsed_var=$(echo "scale=6; $i/$max_var"|bc)

    # expand variables
    f $parsed_var $max_var &
    shift
done
wait                            
Run Code Online (Sandbox Code Playgroud)

另请注意,GNU睡眠处理分数,但许多其他操作系统不处理.