This is an old revision of the document!


Arithmetic evaluation (command)

(( <EXPRESSION> ))

This command evaluates the arithmetic expression <EXPRESSION>.

If the expression evaluates to 0 then the exit code of the expression is set to 1 (FALSE). If the expression evaluates to something else than 0, then the exit code of the expression is set to 0 (TRUE). For this return code mapping, please see this section.

The functionality basically is equivalent to what the ''let'' builtin command does. The arithmetic evaluation compound command should be preferred.

### A moderately complex example that looks for files matching a pattern in certain places, and counts hits.
### Ran under `bash --version` == GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
 
TEMP_FILE="$(mktemp)"
USER='special
PATTERN='run*'
 
# MAXDEPTH='4' # gets total found==88
# MAXDEPTH='5' # gets total found==88
MAXDEPTH='6' # gets total found==88, so I quit
 
let N_FOUND_TOTAL=0
 
# note no spaces in list! spaces are interpreted as word breaks
for N in {2,4,5,6,7,8,9,10,17,18,19} ; do
  SEARCH_ROOT="/project/inf${N}w/${USER}"
  # note change in FIND_CMD compared to previous CMD
  FIND_CMD="find ${SEARCH_ROOT}/ -maxdepth ${MAXDEPTH} -type f -perm '-u+x' -name '${PATTERN}' 2> /dev/null"
  # prevent problems with `ls -alt $(${FIND_CMD})` if FIND_CMD returns nothing
  echo -e "$ ${FIND_CMD} > ${TEMP_FILE}"
  eval "${FIND_CMD} > ${TEMP_FILE}"
  let "N_FOUND_HERE = $(wc -l < ${TEMP_FILE})"
  let "N_FOUND_TOTAL += N_FOUND_HERE"
  if [[ "${N_FOUND_HERE}" -eq 0 ]] ; then
    echo -e "'${PATTERN}' not found under '${SEARCH_ROOT}/'"
  else
    ls -alt $(cat ${TEMP_FILE})
  fi
  echo # newline
done
echo -e "total found==${N_FOUND_TOTAL}"
 
### produces (excerpted) output like
 
# $ find /project/inf4w/special/ -maxdepth 6 -type f -perm '-u+x' -name 'run*' 2> /dev/null > /tmp/tmp.ofCnd30286
# -rwxr--r-- 1 special group 18755 Sep  6 10:28 /project/inf4w/special/runs/oceans/run.oceans.jun
# -rwxr--r-- 1 special group 18681 Jul 29 14:16 /project/inf4w/special/runs/master/run.master.jun
# -rwxrwxr-x 1 special group   997 Jul  3 09:37 /project/inf4w/special/crops_2006/run_usa.sh
# -rwxrwxr-x 1 special group   517 Jul  1 12:33 /project/inf4w/special/crops_2006/run_canada.sh
 
# ...
 
# $ find /project/inf7w/special/ -maxdepth 6 -type f -perm '-u+x' -name 'run*' 2> /dev/null > /tmp/tmp.ofCnd30286
# -rwxr--r-- 1 special group 19696 Dec  5  2012 /project/inf7w/special/runs/nlcd50/run.nlcd50.jun
 
# ... and eventually
 
# total found==88

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
You could leave a comment if you were logged in.
  • syntax/ccmd/arithmetic_eval.1383610564.txt
  • Last modified: 2013/11/05 00:16
  • by tomroche