3

I have the following command in my bash script:

printf '\n"runtime": %s' "$(bc -l <<<"($a - $b)")"

I need to run this script on around 100 servers and I have found that on few of them bc is not installed. I am not admin and cannot install bc on missing servers.

In that case, what alternative can i use to perform the same calculation? Please let me know how the new command should look like

all_techie
  • 2,761
  • 2
  • 11
  • 19
  • **Workaround** to use a subset of the bc functionality without installation: The init(cpio|ramfs|rd) mechanism of your distro should provide a busybox binary which is likely to have bc applet enabled. E.g. on Arch the package [linux](https://archlinux.org/packages/core/x86_64/linux/) depends on [mkinitcpio-busybox](https://archlinux.org/packages/core/x86_64/mkinitcpio-busybox/). The latter provides ``/usr/lib/initcpio/busybox``, and ``$ /usr/lib/initcpio/busybox bc <<<"33-22"`` yields ``11``. – Darren Ng Jan 08 '22 at 09:33

2 Answers2

7

In case you need a solution which works for floating-point arithmetic you can always fall back to Awk.

awk -v a="$a" -v b="$b" 'BEGIN { printf "\n\"runtime\": %s", a-b }' </dev/null

Putting the code in a BEGIN block and redirecting input from /dev/null is a common workaround for when you want to use Awk but don't have a file of lines to loop over, which is what it's really designed to do.

tripleee
  • 175,061
  • 34
  • 275
  • 318
5

If you are only dealing with integers you can use bash's arithmetic expansion for this:

printf '\n"runtime": %s' $((a - b))

Note that this does assume you have bash available (as you've indicated you do). If you only have a stripped down Bourne shell (/bin/sh) arithmetic expansion is not available to you.

Turn
  • 6,656
  • 32
  • 41
  • This presupposes that you have Bash or a similar shell on all the remote servers. The OP probably does (after all, they used `<< – tripleee Jan 31 '18 at 05:18
  • 2
    @tripleee It felt like a safe assumption given that they tagged the question with `bash` and specifically said "bash script" in the title. – Turn Jan 31 '18 at 05:19
  • Sure, it's just that many visitors are probably baffled that "shell script" and "Bash script" are not necessarily synonymous. I'm thinking of future visitors more than the OP. – tripleee Jan 31 '18 at 05:22
  • @tripleee Fair enough – Turn Jan 31 '18 at 05:22
  • Inside the arithmetic context you don't actually need the dollar signs before the variables `a` and `b` – tripleee Jan 31 '18 at 05:25
  • Now that I didn't know. Thanks! – Turn Jan 31 '18 at 05:25
  • 6
    `$((..))` is POSIX, so that's not a problem. I'd be more worried about having to support non-integers – that other guy Jan 31 '18 at 05:28