Skip to main content

3 posts tagged with "Shell"

View all tags

Aliyun CLI Exit 0 but Failed? jq Default Values Hide Errors

Β· 6 min read

An automation script probed whether a Cloud Assistant command still existed using DescribeCommands with a jq -r '.TotalCount // 0' fallback β€” the API returned an error, the script read TotalCount=0, concluded "command doesn't exist," and dutifully created a duplicate.

Encountered this while running managed hosting for a leading manufacturer's China site β€” Cloud Assistant automation is the dispatch channel for patrols and maintenance on that server.

TL;DR​

Two layers stack into one illusion. Layer one: the aliyun CLI prints API error JSON to stderr with exit code 0, so set -e gets no signal. Layer two: the jq -r '.TotalCount // 0' fallback turns an error response β€” which has no TotalCount field β€” into 0, disguising "query failed" as "query succeeded, zero hits." The house rule: capture with 2>&1, read the raw response first, and never use a jq default as a failure probe. Two more landmines nearby: DescribeCommands takes the singular --CommandId (the array-style --CommandId.1 belongs to InvokeCommand habits and is an error here), and DescribeInvocationResults only accepts a CommandId with object-in-object nesting.

Symptoms: the command exists, the script says it doesn't​

The flow is the classic three-step Cloud Assistant pattern: CreateCommand for a CommandId, InvokeCommand to dispatch, DescribeInvocationResults to read back. Before invoking, the script checks the command object:

# existence probe (buggy)
resp=$(aliyun ecs DescribeCommands --CommandId.1 "c-xxx" 2>&1)
count=$(echo "$resp" | jq -r '.TotalCount // 0')
[ "$count" -eq 0 ] && aliyun ecs CreateCommand ... # judged missing β†’ recreate

In practice this walked into the recreate branch on every run: the command was created in the previous round, yet judged missing in this one. Worse, invoking the freshly recreated CommandId could still hit InvalidCmdId.NotFound β€” the new object isn't ready yet, so both the probe and the recreate were wasted work. Left unfixed, the loop kept burning quota.

Root cause: errors exit 0, and jq washes them into defaults​

Two independent facts compose the trap. On the CLI side, API-level errors are printed to stderr while the process exit code stays 0 β€” exit-code-based defenses like set -e never fire. On the jq side, 2>&1 does carry the error JSON into the pipe, but the object has no TotalCount field, so the // 0 fallback helpfully outputs 0. "API call failed" has been laundered into "call succeeded, zero commands found."

--CommandId.1 is a third, smaller fact: the array-style suffix is the parameter habit of InvokeCommand --InstanceId.1, while DescribeCommands wants the singular --CommandId. The wrong form produces yet another error response, silently swallowed by the same fallback.

Fix: raw response first, jq without fallback probes​

The principle in one line: establish what the response is before asking what a field equals. In code, treat a missing TotalCount as failure instead of as zero:

resp=$(aliyun ecs DescribeCommands --CommandId "c-xxx" 2>&1)  # singular flag, capture stderr

# no TotalCount field = API-level failure: print raw and abort, no defaults
echo "$resp" | jq -e '.TotalCount' >/dev/null 2>&1 \
|| { echo "API call failed: $resp"; exit 1; }

count=$(echo "$resp" | jq -r '.TotalCount')
[ "$count" -eq 0 ] && aliyun ecs CreateCommand ... # only now is "missing" trustworthy

jq -e '.TotalCount' exits non-zero when the field is absent β€” it replaces // 0 by escalating "field not found" into an explicit failure. The raw response $resp prints alongside the error, so a human can tell a parameter mistake from a server-side error at a glance.

One boundary worth adding: a CommandId returned by CreateCommand doesn't guarantee the object is usable β€” invoke may still report InvalidCmdId.NotFound while DescribeCommands already counts TotalCount=1. So after recreating, verify existence before invoking; on NotFound, recreate β€” with the raw-response reading above, never with another fallback.

Reading results: nesting and the two IDs​

The read-back side has its own silent failures. DescribeInvocationResults nests objects inside objects; the correct path is:

jq -r '.Invocation.InvocationResults.InvocationResult[0].Output' \
<<< "$resp" | base64 -d

Writing it with array intuition as .InvocationResults[0] throws Cannot index object with number β€” the failure is in the accessor, and the data is already in the response. The other confusion source is the ID system: InvokeCommand returns an InvokeId (t- prefix), while DescribeInvocationResults only accepts a CommandId (c- prefix); if only the InvokeId is at hand, exchange it via DescribeInvocations --InvokeId first. When polling, terminal states are exactly Success and Failed, and results deserve a ~10-second wait after dispatch.

Cloud Assistant pitfalls travel in sets: dispatched content can get corrupted (heredoc assembly) and background jobs get killed (nohup) β€” see Aliyun RunCommand Corrupts Files? Ship base64, Not heredoc and Aliyun Assistant Kills nohup Jobs? Escape with setsid.

Notes

  • Always capture aliyun CLI calls with 2>&1 and judge the response text; the exit code is untrustworthy (errors also exit 0).
  • Never use jq // default as a failure probe β€” a missing field should fail loudly, not default to zero.
  • DescribeCommands takes singular --CommandId; the array-style .1 suffix belongs to InvokeCommand.
  • DescribeInvocationResults only accepts a CommandId; the path is .Invocation.InvocationResults.InvocationResult[0].

FAQ​

What should I watch out for when parsing aliyun CLI output with jq?​

The biggest trap is fallback defaults: jq -r '.TotalCount // 0' prints 0 on an error response instead of failing β€” error JSON goes to stderr with exit code 0, and when TotalCount is missing, the default washes the failure into a legitimate-looking empty result. Capture the raw response with 2>&1 and read it before applying jq, and never use a // default as a failure probe.

Why does the aliyun CLI return success even when the API call failed?​

The CLI prints API-level error JSON to stderr while the process exit code stays 0 β€” set -e and || exit never see it. Failure detection must be based on response content (error code / message fields), never on the exit code.

Why can't DescribeInvocationResults read my results?​

Two common causes. Wrong nesting: the result is an object inside an object, and the correct path is .Invocation.InvocationResults.InvocationResult[0] β€” the array-style .InvocationResults[0] throws Cannot index object with number even though the data is right there. Mixed IDs: DescribeInvocationResults only accepts a CommandId (c- prefix); if all you have is an InvokeId (t- prefix), exchange it first via DescribeInvocations --InvokeId.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Aliyun RunCommand Corrupts Files? Ship base64, Not heredoc

Β· 5 min read

Inside an Aliyun Cloud Assistant RunCommand script, PHP files assembled with a quoted heredoc plus sed kept failing to parse on the instance β€” and every parse error landed on the line where the file says exit 1.

Encountered this while running managed hosting for a leading manufacturer's China site β€” RunCommand is the main channel for patrols and automated maintenance on that server.

TL;DR​

Two rules came out of this. First, never assemble complex code files inside the RunCommand script: generate locally, embed as base64, decode once on the instance β€” after the switch, two consecutive dispatches passed clean. Second, encode exactly once: --CommandContent is already base64-transported, and double-encoding the script fails with command not found (rc=127). The corruption trigger itself stays unidentified β€” exit 1 was the common marker of every failed file, but neither ! nor brace interpolation reproduces it alone.

Symptoms: RunCommand-dispatched files fail to parse at the exit 1 line​

The script's shape was assemble-on-instance, execute immediately:

cat > /tmp/check.php <<'EOF'
<?php
// …bail out when a condition fails
exit 1;
EOF
sed -i 's|placeholder|actual|' /tmp/check.php
wp eval-file /tmp/check.php

The result was a parse error, not the script's own business check:

PHP Parse error: unexpected integer "1"
# error position = the exit 1 line of each failing file

Three observations narrowed things fast: the parse position was exactly the exit 1 line every time; eval files without exit 1 in the same script parsed and ran fine; and running the identical heredoc+sed pipeline locally produced byte-perfect files. The damage lived only on the "dispatched via RunCommand, assembled on the instance" path β€” heredoc syntax itself was not the problem.

Detour: the trigger narrows, the mechanism never lands​

The first suspect was ! β€” history expansion and PHP's !function_exists both seemed plausible. Re-reading the execution record killed it: the very first failing script contained a heredoc with !function_exists that parsed and ran fine, so ! alone doesn't trigger anything. Interpolation braces went next; rewording {} didn't reproduce the corruption either.

After the eliminations, one common trait remained across every failing file: the exit 1 marker. But a shared trait is not a proven trigger, and going further would mean gambling on a mechanism. The operational call was to stop chasing it and change the path instead: move assembly back to the local machine and route around the unexplained corruption.

Fix: generate locally, embed base64, decode once​

All content generation moves local; the script keeps only decode-and-run:

# Local: generate the full file, encode it, paste into the script text
base64 -w0 check.php
# β†’ one base64 line, goes into the B64 variable below
# RunCommand script: decode to disk, no on-instance assembly
B64='PGhwCi8v…'
echo "$B64" | base64 -d > /tmp/check.php
wp eval-file /tmp/check.php

Verification: after the switch, two follow-up dispatches (test-attachment cleanup and a probe script) both passed clean β€” no more parse errors.

The second pitfall is about encoding layers. CreateCommand receives --CommandContent as base64 β€” the caller encodes the script text once, the service decodes once and runs it. Encoding twice makes the server decode into another base64 string, which then gets executed as a script:

# Wrong: encoding the script body twice
base64 -w0 script.sh | base64 -w0 > doubled.txt
# CreateCommand --CommandContent "$(cat doubled.txt)"
# β†’ server decodes once, executes base64 text β†’ command not found, rc=127

Encode once. The base64 around embedded files is a separate layer (encoding of the file content) and has nothing to do with the script's own transport encoding.

Silent Cloud Assistant behavior doesn't stop here β€” once the invocation returns, background jobs started with nohup inside the script get cleaned up with the session; the fix is covered in Aliyun Assistant Kills nohup Jobs? Escape with setsid.

Notes

  • Complex code files: always generate locally and ship base64-embedded; keep on-instance heredoc+sed for simple config snippets only.
  • --CommandContent is encoded exactly once; double encoding fails with command not found (rc=127).
  • An unidentified mechanism means no safe boundary: don't treat "my content has no exit 1" as an exemption β€” avoiding the assembly path is the stable policy.
  • A Success result only means the script finished, not that background jobs it started are still alive.

FAQ​

Why is the same content fine locally but corrupted through Cloud Assistant?​

The only difference between the two paths is the on-instance assembly step: the same heredoc+sed pipeline produces byte-perfect files locally, while files assembled inside the RunCommand script get corrupted at the line carrying an exit 1 marker. The trigger is unidentified (! and brace interpolation alone don't reproduce it), but the avoidance rule is settled β€” don't assemble complex code files inside RunCommand scripts.

How should files be delivered through Cloud Assistant?​

Generate the full file content locally, base64-encode it, embed it in the RunCommand script, and decode once on the instance with base64 -d. After switching, two consecutive dispatches passed clean. Mind the encoding layers: --CommandContent is itself base64-transported, so the script body is encoded exactly once β€” double encoding fails with command not found (rc=127).

Can heredoc still be used inside RunCommand scripts?​

At the time, simple eval files without exit 1 in the same script parsed and ran fine; the corruption clustered around assembled PHP code files. But with the mechanism unidentified, the safe boundary can't be drawn β€” production scripts should avoid assembling code on the instance entirely and ship complex files as locally generated, base64-embedded payloads.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

grep -P fails in scripts, works in your shell? PATHs differ

Β· 6 min read

A release script that had run unattended on WSL for months died on its first grep call the day it was moved to a Mac: grep: invalid option -- P. What made it worse was the diagnostic itself β€” typing the very same grep -oP '…' into the terminal passed. Same command, same machine: works in the terminal, fails in the script.

TL;DR​

  1. The error has nothing to do with a typo: your interactive zsh and the bash script resolve two different PATHs. Interactively, grep hits a brew-installed GNU grep (which supports -P); in the script it hits /usr/bin/grep (BSD grep, no -P).
  2. The same family of failures extends beyond grep: sha256sum and other GNU coreutils tools exist only in the interactive PATH too, and fail with command not found one step later.
  3. Three portable fixes: rewrite every grep -oP as an equivalent sed -nE extraction; fall back to shasum -a 256 when sha256sum is missing; replace hardcoded paths with runtime self-detection. The script then runs on any machine, any shell.