3

I have a bunch of commands whose execution should only occur after the successful completion of past commands. I initially started using && to get the job done, but that started resulting is some pretty long lines of code.

I decided to try to make a script of my own that could accomplish the same task, but allow me to do it one line at a time. I've called it thenDo, and here's what I've got:

#!/bin/bash

errorCode=$?
if [[ $errorCode -eq 0 ]]; then
  $@
  errorCode=$?
fi
return $errorCode

I've tried running this with a bunch of various modifications to see what the value of $? was at various stages of execution. It looks like this script will always start with a clean slate, as in the starting value of $? is always 0.

For now, I've made a function in my .bashrc, and that seems to work just fine in my shell, but I need this script so that it can be used within other scripts, which are called by other scripts again, and it seems that this function doesn't always persist through various and sometimes nested script invocations.

It would be really nice if I could find a way to do this in its own script instead of a function. Is there any way to make that happen?

sbrun
  • 197
  • 2
  • 13
  • Add `set -e` at the start of the script or change the shebang to `#!/bin/bash -e` or manually start with `bash -e scriptfile` – anishsane May 05 '16 at 07:52
  • Is there a reason you want a script instead of a function ? – 123 May 05 '16 at 07:55
  • In answer to your question - no, you cannot do it in a script because your script will be a new bash process and its will not see or know the exit status of a command that ran in its parent. Walter A's advice of using a function library and sourcing it into your other scripts is the way to go. By the way you can propagate functions into subshells with `export -f someFunction` – Mark Setchell May 05 '16 at 12:34

1 Answers1

1

When you want to have functions shared by various scripts, consider making a directory with some utility scripts and source these scripts.
Perhaps you need to use find dir of current script to find your util lib relative to the script running.

# example file sourcing files in your own dir, stored in the var `shlib`.
source "${shlib}"/thenDo
source "${shlib}"/sqlutils

In your case, I would not use the thenDo solution, but use a backslash for writing your command in several lines:

action1 && 
action2 with a lot of arguments that \
  may continue on the next line when \
  you end each line with a backslash \
  except at the end of your command  && 
action3 && 
action4 |
   pipe_also_does_not_need_backslash && 
action5

Only remember that the \ must be the last char of the line (no spaces after it).

Community
  • 1
  • 1
Walter A
  • 19,067
  • 2
  • 23
  • 43
  • I didn't actually know that you could put the `&&` at the end of a line, and then put the next command on the next line. This totally negates the need for my script in the first place! Thanks! :) – sbrun May 05 '16 at 20:21