Use of Flags in Bash Script

Use of Flags in Bash Script

Scripts in linux start with some declaration like :

#!/bin/bash

Correct me if I am wrong : this probably says which shell to use.

I have also seen some scripts which say :

#!/bin/bash -ex

what is the use of the flags -ex

1

3 Answers

#!/bin/bash -ex

<=>

#!/bin/bash
set -e -x

Man Page ():

-e  Exit immediately if a simple command exits with a non-zero status, unless
   the command that fails is part of an until or  while loop, part of an
   if statement, part of a && or || list, or if the command's return status
   is being inverted using !.  -o errexit

-x  Print a trace of simple commands and their arguments
   after they are expanded and before they are executed. -o xtrace

UPDATE:

BTW, It is possible to set switches without script modification.

For example we have the script t.sh:

#!/bin/bash

echo "before false"
false
echo "after false"

And would like to trace this script: bash -x t.sh

output:

 + echo 'before false'
 before false
 + false
 + echo 'after false'
 after false

For example we would like to trace script and stop if some command fail (in our case it will be done by command false): bash -ex t.sh

output:

+ echo 'before false'
before false
+ false

These are documented under set in the SHELL BUILTIN COMMANDS section of the man page:

  • -e will cause Bash to exit as soon as a pipeline (or simple line) returns an error

  • -x will case Bash to print the commands before executing them

-e

is to quit the script on any error

-x

is the debug mode

Check bash -x command and What does set -e mean in a bash script?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.