0

I need to make a script in bash to keep a running count based on user keyboard input

if i type "1" i want a variable $h to increment +1

if i type "2" i want a variable $L to decrement -1

and i want to have variable $c output the sum of the first two variables.

i have tried this: to no avail

#!/bin/bash

h='0'
l='0'

read card

if [$card='1']
then 
  let "h++"
fi
if [$card='2']
then
  let "l--"
fi

c=$(($h+$l))

echo $c`

Where am i screwing up?

1
  • [ $card -eq 1 ] - wrong, the [ must have spaces and -eq must be used for arithmetic comparison

  • $c <- you had a trailing backtick there, so remove it.

  • Not wrong but just a suggestion: let var++ don't need double quotes and $((var++)) don't need $ ( the "deference" operator, so to speak).
  • Not wrong, but unnecessary: single quotes in number assignment h=0

Whole idea of "running count" can be a problem: your script is sequential, so by definition variables will be gone once script exits. Your running count won't be counted simply because that's how shell works. What you might wanna do is output counters to temp file, and read them back. Alternatively, make your script run in infinite while loop. Something like:

#!/bin/bash
h=0
l=0
while read user_input;
do
    [ "$user_input" -eq 1 ] && ((h++))
    [ "user_input" -eq 2 ] && ((l--1))

    echo "So far h is $h, and l is $l"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.