How to avoid a shell script exiting on failure for particular commands

StackOverflow https://stackoverflow.com/questions/23415794

  •  13-07-2023
  •  | 
  •  

سؤال

The following script runs with the -e option, so it will exit if any of the commands in it fail:

#!/bin/sh -e
command1 #script should fail if command1 fails
command2 #script should NOT fail if command2 fails
command3 #script should fail if command3 fails

How can I make the script not to fail on command2?

هل كانت مفيدة؟

المحلول

command1
command2 || true
command3

نصائح أخرى

You could turn off the setting as required:

#!/bin/sh
set -e

command1 #script should fail if command1 fails

set +e
command2 #script should NOT fail if command2 fails
set -e

command3 #script should fail if command3 fails

if you are running a command in shell that exits you can prevent it by running it inside a sub-shell:

(. script.sh)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top