Bash 3.0

Version of implementation Bash of programming language Unix shell

Bash 3.0 provides a number of bug fixes and cleanups to the features introduced in the previous several releases.

Examples:

Factorial - Unix shell (48):

This example uses recursive factorial definition.

factorial ()
{
    local num=$1;
    if [ $num = 0 ]; then
        echo 1
        return ;
    fi;
    echo $(( $num * $(factorial $(( $num - 1 )) ) ))
}

for ((n = 0; n <= 16; n++))
do
    echo "$n! = " $(factorial $(($n)))
done

Hello, World! - Unix shell (202):

This example demonstrates script declaration line, comment, variables and difference between single and double quotes. This is likely enough for Hello. As it should be in bash, message can be configured through parameters.

# Prints "Hello world" message in Bash, Unix shell.

MESSAGE='hello'
TARGET='world'

echo "$MESSAGE $TARGET"

Quadratic equation - Unix shell (275):

Bash itself can’t process floating-point numbers, so to calculate roots we have to use bc.

read A;
if [ $A = 0 ]; then
    echo "Not a quadratic equation.";
    exit 0;
fi
read B;
read C;
D=$(( ($B)*($B)-4*($A)*($C) ));
#integer math only!
if [ $D = 0 ]; then
    echo -n "x = "
    echo -e "scale=3\n-0.5*($B)/($A)" | bc
    exit 0;
fi
echo $D
if [ $D -gt 0 ]; then
    echo -n "x1 = "
    echo -e "scale=3\n0.5*(-($B)+sqrt($D))/($A)" | bc
    echo -n "x2 = "
    echo -e "scale=3\n0.5*(-($B)-sqrt($D))/($A)" | bc
else
    echo -n "x1 = ("
    echo -e "scale=3\n-0.5*($B)/($A)" | bc
    echo -n ", "
    echo -e "scale=3\n0.5*sqrt(-($D))/($A)" | bc
    echo ")"
    echo -n "x2 = ("
    echo -e "scale=3\n-0.5*($B)/($A)" | bc
    echo -n ", "
    echo -e "scale=3\n-0.5*sqrt(-($D))/($A)" | bc
    echo ")"
fi