Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of flags in bash script

Tags:

linux

bash

shell

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

like image 239
iwekesi Avatar asked Sep 24 '16 04:09

iwekesi


Video Answer


3 Answers

#!/bin/bash -ex

<=>

#!/bin/bash
set -e -x

Man Page (http://ss64.com/bash/set.html):

-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
like image 188
pavnik Avatar answered Oct 12 '22 05:10

pavnik


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

like image 35
Matei David Avatar answered Oct 12 '22 04:10

Matei David


-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?

like image 25
Gilles Quenot Avatar answered Oct 12 '22 06:10

Gilles Quenot