There is a disease called code specification obsessive-compulsive disorder, do not know the specification do not know how to start writing code, must first read the code specification!

background

I have read Google’s Shell scripting specification, which states:

Declare function-specific variables using local. Declarations and assignments should be on different lines.

When the assigned value is provided by a command substitution, the declaration and assignment must be separated. Because the built-in local does not pass an exit code from command substitution.

Hit the pit

Follow the specifications

Since then, whenever I define a variable using local, I’ve written something like this:

local image_id
image_id=$(docker images | grep my_container)
Copy the code

There is a problem

No problem, the above is really standard. However, when set-e is used in a shell script, if grep does not match the content, the entire script exits at variable assignment time.

If grep does not match any content, the exit code is 1.

$ grep -vE '^' [.]< < < $'.\n.'; echo $?
1
Copy the code

From the pit

Methods a

Use set +e before grep and set -e after grep:

local image_id

set +e
image_id=$(docker images | grep my_container)
set -e
Copy the code

Way 2

local image_id
image_id=$(docker images | grep my_container) || true
Copy the code

Methods three

Sometimes it’s ok not to follow the rules

local image_id=$(docker images | grep my_container)
Copy the code

conclusion

There is no problem with Google’s specification. After all, grep is not used very thoroughly!

Original link: k8scat.com/posts/use-l…