I am working on an exam practice problem in which we need to invoke a script on a file. If the exit status is non-zero, we increment the number of fails by one, else we increment the sum variable by one. Since we don't actually have this script, I just wanted to verify that what I wrote on paper is correct, assuming that the script we are calling is called compute, and args are all the file arguments.
SUM=0
NUMFAILS=0
SCRIPT=./$compute
for args in *; do
num=$SCRIPT args
if (($? -ne 0)); then
NUMFAILS++
else
SUM=(($SUM+$num))
fi
done
$?for testing exit status of the last command or you can test it withifdirectly:if command; then echo CMD OK; fiif output=$(command); then echo CMD OK; fiNUMFAILS++: you still need to use((to evaluate the expression:((numfails++))num=$SCRIPT args: you need to use command substitution to substitute the output of a command:num=$(./script "$args")argsis a variable, you need to expand it with a dollar sign:"$args". Quotes are necessary to prevent word-splitting. Note that in arithmetic context, for example((++numfails)), you don't need to use dollar signshopt -s nullglobto skip theforloop if there are no files in your directoryset -e, you should use preincrement((++numfails))and((sum+=num)) || trueto handle cases whereset -ewould terminate the script when the result of either arithmetic expression is equal to 0