如何在终端检查Docker镜像是否存在及编写条件判断语句
Got it, let's break this down clearly—your original if syntax has a few shell scripting mistakes, and we'll fix that while building a reliable check for your Docker image.
First: Why Your Original If Statement Fails
Your line if [docker source:anything] docker tag source:anything target:something fi has two critical issues:
- The
[(shorthand for thetestcommand) requires spaces around it and valid arguments—docker source:anythingisn't a valid test condition. - Shell
ifstatements run a command and check its exit code (0 = success, non-0 = failure) directly—you don't wrap the command in[ ]unless you're using test operators like file checks or string comparisons.
Correct Approach: Check Image Existence First
To verify if a source image exists locally, the most reliable command is docker inspect—it returns an exit code of 0 if the image exists, and non-0 if it doesn't. We'll silence its output so it doesn't clutter your terminal.
Here's a complete, working script/command sequence:
# Define your images for clarity (optional but recommended) SOURCE="source:anything" TARGET="target:something" # Check if source image exists, then tag if docker inspect --type=image "$SOURCE" > /dev/null 2>&1; then echo "Source image $SOURCE found—tagging to $TARGET..." docker tag "$SOURCE" "$TARGET" else echo "Error: Source image $SOURCE does NOT exist locally!" # Exit with an error code if you're using this in a script exit 1 fi
Let's break down each part:
docker inspect --type=image "$SOURCE": Ensures we're only checking for images (not containers) with the exact name/tag you specified.> /dev/null 2>&1: Redirects both standard output and error output to the null device—we only care about the exit code, not the actual inspection output.- The
ifdirectly runs thedocker inspectcommand: If it exits successfully (code 0), we run thedocker tagcommand. If not, we print an error and exit (optional but useful for scripts).
Alternative: Using docker images (Less Reliable)
You could also filter the output of docker images, but docker inspect is better because it avoids false positives (e.g., partial name matches). If you still want to use this method:
if docker images --format '{{.Repository}}:{{.Tag}}' | grep -q "^$SOURCE$"; then docker tag "$SOURCE" "$TARGET" else echo "Error: Image $SOURCE not found!" fi
Key Shell Scripting Takeaways for If Statements
- Run commands directly in
if: Useif command; then ... fiwhen you want to check if a command succeeds. - Use
[ ]for test conditions: Only wrap things in[ ]when using comparison operators (e.g.,if [ -f file.txt ]; then ...to check if a file exists). - Always quote variables: Using
"$SOURCE"instead of$SOURCEprevents issues if your image name has spaces (uncommon for Docker, but good practice).
内容的提问来源于stack exchange,提问作者user3142695

