bash - set -e makes function stop running early? -


i have function seems break when turn on errors set -e. suspect working intended can't see i'm doing wrong.

here function:

#!/usr/bin/env bash  set -e  my_function() {     base_dir="/tmp/test"     if [ ! -d $base_dir ];         echo "creating $base_dir"         mkdir -p $base_dir         touch $base_dir/some-file.txt     fi      is_edited=$(grep "foo" $base_dir/some-file.txt)      if [ ! -z $is_edited  ];         cd $base_dir         echo "doing stuff"         docker run --rm debian ls     fi      echo     echo "done"     echo }  my_function 

with set -e flipped on, function returns seemingly without hit echo statements. set -e turned off, echo statements hit. happening , how fix this?

try using:

is_edited=$(grep "foo" $base_dir/some-file.txt || test $? -eq 1) 

the exit status of grep 0 if found match, 1 if didn't find match, , 2 if got actual error. if there's no match foo in file, considered error, , set -e terminate script. above code translates 1 success, script terminate if grep gets real error.

if don't care terminating script if grep gets error, use

if grep -1 "foo" $base_dir/some-file.txt ;     ... fi 

the -q option makes not print matching line, set exit status based on whether found match.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -