You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本输出格式优化请求:去除空行及多余空格

Fixing Shell Script Output Format for Mount Status Check

Let's tackle those extra spaces and empty lines in your script's output—here's how to get clean, properly formatted results:

What's Wrong With the Original Script

The main issue is how you're collecting and printing results. When you store loop output in the mount_check array, empty entries can sneak in (from mount points that are mounted, since your loop only outputs something when they're not). Plus, using echo ${mount_check[*]} joins array elements with spaces, leading to messy spacing and empty lines when there are gaps in the array.

Solution 1: Direct Output (Simplest & Most Efficient)

Skip the array entirely and print results immediately as you check each mount point. This avoids array-related formatting headaches:

#!/bin/bash

# Filter relevant mount points from /etc/fstab (skip bind, swap, shm, comments, empty lines)
while IFS= read -r mount_point; do
    # Check if the mount point is unmounted (suppress findmnt's output)
    if ! findmnt -m "$mount_point" >/dev/null 2>&1; then
        echo "File system $mount_point is NOT mounted"
    fi
done < <(awk '!/bind|swap|shm/ && $1 !~/#|^$/ && !/^ +$/ { print $2 }' /etc/fstab)

Why This Works:

  • The while read loop processes each mount point one by one.
  • findmnt -m "$mount_point" >/dev/null 2>&1 silences all output from findmnt—we only care about its exit status to know if the mount is missing.
  • We print the message only when a mount point is unmounted, so no empty lines or extra spaces creep in.

Solution 2: Use Array Properly (If You Need to Store Results)

If you must keep results in an array for later use, make sure you only add valid messages to the array, then print each element on its own line:

#!/bin/bash

# Get filtered mount points
fstable=( $(awk '!/bind|swap|shm/ && $1 !~/#|^$/ && !/^ +$/ { print $2 }' /etc/fstab))

# Initialize empty array to hold error messages
mount_check=()

for mount in "${fstable[@]}"; do
    if ! findmnt -m "$mount" >/dev/null 2>&1; then
        # Add only non-empty messages to the array
        mount_check+=("File system $mount is NOT mounted")
    fi
done

# Print each array element on a new line
printf '%s\n' "${mount_check[@]}"

Why This Works:

  • We explicitly add messages to the array only when a mount point is unmounted—no empty entries.
  • printf '%s\n' "${mount_check[@]}" prints each array element on its own line, with no extra spacing.

Either approach will give you the clean output you want:

File system /abc is NOT mounted
File system /xyz is NOT mounted

内容的提问来源于stack exchange,提问作者rony thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:57:28