Your script:
#!/bin/bash
if [ $# != 2 ]; then
echo "2 arguments are required "
exit
else
x=$1
y=$2
sum = $x + $y
echo ` sum = $sum | bc `
fi
- All variable substitutions should be double-quoted: http://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells
- Arithmetic comparison for inequality is done with
[ ... -ne ... ]
.
- Diagnostic output, i.e. errors and warnings, should go to standard error.
- When exiting on an error condition, a non-zero exit status should be returned to the calling shell.
- Assignments do not accept spaces around
=
.
With these things in mind, your code becomes
#!/bin/sh
if [ "$#" -ne 2 ]; then
echo >&2 'Expected two arguments'
exit 1
fi
printf 'sum = %f\n' "$( printf '%f + %f\n' "$1" "$2" | bc )"
Alternatively, with a couple of bash
extensions:
#!/bin/bash
if (( $# != 2 )); then
echo >&2 'Expected two arguments'
exit 1
fi
printf 'sum = %f\n' "$( bc <<<"$1 + $2" )"
With intermediate variables:
#!/bin/bash
if (( $# != 2 )); then
echo >&2 'Expected two arguments'
exit 1
fi
x="$1"
y="$2"
sum="$( bc <<<"$x + $y" )"
printf 'sum = %f\n' "$sum"
Modify the printf
formatting string to suit your needs. If you, for example, want two decimals, use %.2f
instead of %f
.
./filename.sh 2.4 5
type -a bash
?