Function that increments success or failure counters based on command results

时间:2018-02-07 16:55:28

标签: bash

Currently i need to streamline a script to reduce lines

Success="0"
Fail="0"
Var=$((+1))
red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`
Success-Fail(){if} {then $((Success+=Var))}

if sudo apt-get install ruby-dev; then $((Success+=Var))
else
   $((Fail+=Var))
fi
if sudo gem install rails; then $((Success+=Var))
else
    $((Fail+=Var))
fi
if sudo apt-get install ruby mine; then $((Success+=Var))
else
    $((Fail+=Var))
fi

echo "${green} "Success" $Success ${reset}"

sudo echo "${red} "Fail" $Fail ${reset}"

i need to create a function that gets rid of the if then else and creates it so i just use the function. which will reduce 3 lines for one program down to 1 line.

how should i go about doing this?

1 个答案:

答案 0 :(得分:1)

SuccessFail() { if "$@"; then : $((++Success)); else : $((++Fail)); fi; }

SuccessFail sudo apt-get install ruby-dev
SuccessFail sudo apt-get install rails
SuccessFail sudo apt-get install ruby mine

请注意,如果您使用$(( )),则需要对结果执行某些操作,因为此操作是扩展,因此它会尝试将数学运算的结果视为命令的一部分。如果您想对副作用进行算术运算并忽略其结果,则可以使用bash扩展名(( ))