我对shell脚本不太熟悉。我想为以下伪代码编写一个shell脚本:
min=some garbage value
for(i=1 to N){ // N and n will be taken as input for the shell script.
for(j=1 to n){
val= './a.out' // call the executable a.out and take the output in val
if(val<min) // a.out is a random number generator script
min=val;
}
arr[k++]=min;
}
// Then I want to calculate the sum of the elements of the array 'arr'.
如何通过 shell 脚本来完成这些工作?
a.out
是这样的,它将产生一串数字作为输出。我必须将此字符串转换为变量val
。这个怎么做?例如,作为输出a.out
生成,但它是字符数组而不是浮点数。我想通过 shell 脚本将其转换为浮点数,但我无权更改可执行文件的 C 代码。12.34
12.34
a.out
#!/bin/bash
# set min to some garbage value
min=1
N=$1
n=$2
for (( i=1; i<=$N; i++ )); do
for (( j=1; j<=$n; j++ )); do
val=$(/path/to/a.out)
val2=`echo $val | bc` // is this the correct syntax?
if (( $val2 < $min )); then
min=$val2;
fi
done
arr=("${arr[@]}" "$min")
done
# Then I want to calculate the sum of the elements of the array 'arr'.
sum=0
for (( l=0; l<${#arr[@]}; l++ )); do
sum=$( expr $sum + ${arr[$l]} )
done
echo "Sum of \$arr = ${sum}"
上面的代码对我不起作用。
答案1
Val=$(./a.out)
Val=`a.out`
这两个都将执行a.out
并将输出存储到Val
.
假设使用 bash 或兼容的 shell。
答案2
以下是将您的代码转换为应与 bash 或 ksh 一起使用的脚本:
#!/bin/bash
# set min to some garbage value
min=1
N=$1
n=$2
for (( i=1; i<=$N; i++ )); do
for (( j=1; j<=$n; j++ )); do
val=$(/path/to/a.out)
if (( $val < $min )); then
min=$val;
fi
done
arr=("${arr[@]}" "$min")
done
# Then I want to calculate the sum of the elements of the array 'arr'.
sum=0
for (( l=0; l<${#arr[@]}; l++ )); do
sum=$( expr $sum + ${arr[$l]} )
done
echo "Sum of \$arr = ${sum}"
现在,这是代码的实际翻译。您可能想要更改为数组 $arr 赋值的方式,因为您将 $min 而不是 $val 推入数组,如果 $val 小于 $min,那么您将更改该值$min 的值结转到 $val 的值(直到在循环的后续迭代中找到 $val 的较低值)。
答案3
#!/bin/bash
# define as first and second parameter for script:
N=$1
n=$2
# declare as array:
declare -A arr
k=0
min=7 # some garbage value
# for-loop with variable: Use 'seq'
for i in $(seq 1 $N)
# do...done - not curly braces:
do
for j in $(seq 1 $n)
do
# already explained
val=$(./a.out)
# arithmetic evaluation in double parens:
if (( val < min ))
then
min=$val
fi
done
arr[$k]=$min
k=$((k+1))
done
array=${arr[*]}
addition=${array// /+}
echo $((addition))
感谢 Gilles 在评论中提供的有用提示。