Bash 4.0.35

Version of implementation Bash of programming language Unix shell

A version of Bash implementation.

Examples:

Hello, World! - Unix shell (212):

This example uses dc (Desktop Calculator), which is a popular non-standard tool that allows processing arbitrary-precision numbers. | dc means that dc has to be applied to the command.

P command (the last character before | dc) outputs the last element of the stack. The huge number before P when written in hexadecimal looks as 0x48656C6C6F2C20576F726C64210A; pairs of adjacent digits form ASCII-codes of characters of “Hello, World!”: 0x48 = H, 0x65 = e, 0x6c = l etc. Thus, when printed, this number is processed as a string.

echo 1468369091346906859060166438166794P | dc

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

Fibonacci numbers - Unix shell (213):

a=0
b=1
 
for (( n=1; $n<=16; n=$n+1 ));
do
  a=$(($a + $b))
  echo -n "$a, "
  b=$(($a - $b))
done
echo "..."

Factorial - Unix shell (214):

This example uses iterative factorial definition.

f=1

for (( n=1; $n<=17; $((n++)) ));
do
  echo "$((n-1))! = $f"
  f=$((f*n))
done

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