如何用Shell脚本提取Docker服务前缀(Stack名称)并存入变量
Got it, let's break down how to pull that prefix (your Stack name) from the Docker service name and store it in a shell variable—super straightforward with a few common shell tools.
Method 1: Bash Parameter Expansion (No External Tools Needed)
This is my go-to because it's fast and doesn't require spawning extra processes. Use Bash's built-in string manipulation to strip everything after the first underscore:
# Define your service name variable (replace with your actual service name) SERVICE_NAME="UAT_postgres1.gbc38equ81vj6skoknsu83ypz" # Extract the stack name (everything before the first underscore) STACK_NAME="${SERVICE_NAME%%_*}" # Verify the result echo "Stack Name: $STACK_NAME"
The %%_* syntax means: "remove the longest match of _* starting from the end of the string"—so it cuts off everything from the first underscore onwards.
Method 2: Use cut Command
If you prefer a more explicit field-splitting approach, cut works perfectly here by splitting the string on underscores and grabbing the first field:
SERVICE_NAME="UAT_postgres1.gbc38equ81vj6skoknsu83ypz" STACK_NAME=$(echo "$SERVICE_NAME" | cut -d '_' -f 1) echo "Stack Name: $STACK_NAME"
-d '_': Sets the delimiter to an underscore-f 1: Tellscutto return the first field
Method 3: Use awk Command
Another reliable option is awk, which gives you flexibility if you ever need to handle more complex patterns later:
SERVICE_NAME="UAT_postgres1.gbc38equ81vj6skoknsu83ypz" STACK_NAME=$(echo "$SERVICE_NAME" | awk -F '_' '{print $1}') echo "Stack Name: $STACK_NAME"
-F '_': Sets the field separator to an underscore{print $1}: Prints the first field of the split string
Add Error Handling (Optional)
If you want to make sure the service name actually has an underscore (to avoid unexpected results), add a quick check:
SERVICE_NAME="UAT_postgres1.gbc38equ81vj6skoknsu83ypz" if [[ ! "$SERVICE_NAME" =~ "_" ]]; then echo "Error: Service name doesn't contain an underscore—can't extract stack name!" exit 1 fi STACK_NAME="${SERVICE_NAME%%_*}" echo "Stack Name: $STACK_NAME"
内容的提问来源于stack exchange,提问作者James Taylor

