K
K
ksvdon2014-06-18 23:49:08
bash
ksvdon, 2014-06-18 23:49:08

Using a function within a function. Is it possible in bash?

Made a function to check the status. And separate functions for some script checks. I use functions in order to be able to specify an (intermediate) exit code through return and at the same time continue the script (and generally convenient). And the function for checking the status just looks at the intermediate exit code. And if the code is not what is expected, it increments the error counter. It would be great to do the check directly in the function, and not at the output, so that some additional lines would not spoil my "prepared return". Is it possible to do this somehow? Because I see that inserting a function into a function is not an option =( In general terms, it looks like this:

check=0
function check-exit-stat()
{ if [ $? -ne $1 ]
  then check=`expr $check + 1`
  fi
}

function f1() 
{ k=1
   if [ $k -eq 0 ]
    then
     return 0
    else
     return 1
   fi
#было бы хорошо тут поставить check-exit-stat 0
}
т.к. если сделать так
f1
check-exit-stat 0
exit $check

then perhaps some additional entries after "fi" can change the exit status from what I indicated with return to any other. And it doesn't work anymore. ps stupidly do not want to increase the counter in the right place ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xotkot, 2014-06-19
@ksvdon

but how do you want to execute something inside the function after return, because return is just intended to exit the function, everything below will simply not be executed.

1) If you don’t have a return there, but a certain command that returns a return code ($?), then you can simply drive it into a variable and output it at the end of the function.
#!/usr/bin/bash

check=0

check-exit-stat() {
  if 
    then ((check++))
  fi
}

f1() {
  k=1
  if 
    then ls # return 0
    else blabla # return 127
  fi
N=${?}
check-exit-stat 0 ${N}
return ${N}
}

f1
echo $?
# ...
f1
echo $?
# ...
echo check=$check
exit $check
2) or even simpler:
#!/usr/bin/bash

check=0

check-exit-stat() {
  if 
    then ((check++))
  fi
  return ${check}
}

f1() {
  k=1
  if 
    then ls # return 0
    else blabla # return 127
  fi
check-exit-stat 0 ${?}
}

f1
echo $?
# ...
f1
echo $?
# ...
echo check=$check
exit $check
3) if you need to use return exactly in that place, then you can do this:
#!/usr/bin/bash

check=0

check-exit-stat() {
  if 
    then ((check++))
  fi
  return ${check}
}

f1() {
  k=1
  if 
    then check-exit-stat 0 0 # return 0
    else check-exit-stat 0 1 # return 1
  fi
}

f1
echo $?
# ...
f1
echo $?
# ...
echo check=$check
exit $check

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question