0

I am trying to write a shell script where there needs to be a try/except loop. How do I do a loop like this in shell?

What I am trying to do is basically this:

password="user's password here"
Try_command_here:
    echo $password | sudo -S apt-get -y purge some-package-here
Except_command_here:
    Re-obtain_user_password

After it reobtains the password it would loop so that it can retry. It would do this 3 times, if needed, and if the correct password has not been provided by then it throws up an error window and exits.

I know in Python the command for this is simply try: and then except:

Is this so for shell or is it something different?

Thanks!!

EDIT

I am targeting the bash shell.

Output of echo $SHELL ===> /bin/bash

Batcastle
  • 170
  • 12
  • Which shell are you targeting in particular? Can you show what `echo $SHELL` is throwing? – Inian May 01 '18 at 15:34
  • 1
    To know if a command/program has failed or succeeded, you can use its [**exit status**](https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html). – Ronan Boiteau May 01 '18 at 15:38
  • @Inian i added the information you requested. – Batcastle May 01 '18 at 15:58
  • BTW, `echo $password` is buggy. Always use quotes: `echo "$password"` -- otherwise, if a password had a `*` in it surrounded by spaces, that would be replaced with a list of filenames; various other unwanted replacements are possible as well (multiple spaces collapsed to just one, trailing spaces removed, bracket expressions parsed as globs, etc). This is also [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo). – Charles Duffy May 01 '18 at 15:58
  • I had not thought of this. Thank you @CharlesDuffy ! – Batcastle May 01 '18 at 15:59
  • @Inian, btw, duplicate question or not, I thought your answer was useful here, insofar as it's customized to what the OP is doing and thus provides specific guidance on how best to apply the generalized answer given in the linked duplicate. If you don't want to get rep from answering a dupe, I'd consider marking it community-wiki rather than deleting, but there's enough of a value-add there that my personal judgment call is that I don't see that as necessarily called for under the circumstances. – Charles Duffy May 01 '18 at 17:39
  • ...granted, @user464502's objection is a thing (and [at least one answer](https://stackoverflow.com/a/5274381/14122) on the linked question explicitly covers the password-reprompt case), but that's going beyond the immediate focus of the question (effectively, "how do we detect and branch on failures in shell logic?") into looking for guidance on distinguishing `sudo` failures from `apt-get` failures, which arguably could/should be an entirely separate question on its own. – Charles Duffy May 01 '18 at 17:42

0 Answers0