Using a shell script and BC

4.2k views Asked by At

I am in many ways extremely new to programming so thank you for putting up with my idiocy because I'm sure I am not asking this in the right way.

I'm having to use a linux machine and a lot of command line stuff for the first time in years. I need to do a Monte Carlo simulation using a cloud model that is written and ready to go. It has an input file that I need to vary set input values in to be generated using some kind of random number generator. My supervisor insists that I use BC to generate random numbers.

My understanding is that BC is a language. I have downloaded it using:

sudo apt-get install bc

Now I think I should try to write some kind of script that makes a copy of the original input file and then searches for the strings in the original file and replaces them with the strings I want it to use. I think I can do this with a shell script?

I do not understand how I can use bc and bash at the same time. If I enter a BC command will it just do it? Does BC execute shell commands? How does this work?

In your answer remember that I am just a lab monkey left with a computer who does not really understand anything about programming.

2

There are 2 answers

0
Gilles Quénot On

One way to interact between shell and bc :

$ echo "$RANDOM % 5" | bc

will print a random number in the range 0 to 4

$RANDOM is a pseudo random integer usable directly in your shell.

Note that double quotes are mandatory to use shell variables. With single quotes, the variables will be never evaluated.

After, you can do arithmetic if you need with and (( )) arithmetic operator :

value=$(echo "$RANDOM % 5" | bc)  # 0 10 4
((value*10))                      # value X 10
echo $value                       # display $value value
echo "scale=2; $value / 100" | bc # scale=display 2 decimal
1
Tim B On

You can use bc within a shell script, for example

#!/bin/bash

# Generate random number between 0 and 9
RANDVAR=$(echo "$RANDOM % 10" | bc)
echo $RANDVAR

This simple script shows how you can assign a variable a name and use it later in the script. Anything in "$()" will be run, and the result assigned to the name (in this case RANDVAR). You can use this variable later in your substitution using, for example, sed.