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

SSH多主机执行mkdir创建同名文件夹,Ksh脚本报错排查求助

Let's work through fixing your script and understanding why that error is popping up.

What's Causing the mkdir Usage Error?

The error message tells us mkdir isn't getting valid arguments, which ties directly to how your script handles the $i variable and reads hostnames:

  1. Broken hostname reading: Using for i in \cat $1`splits yourhostnameListfile by *all whitespace* (spaces, tabs, newlines) instead of just lines. If your list has empty lines or hostnames with spaces,$ican end up empty or split into multiple values—leading tomkdir` running with no arguments (triggering the usage error).
  2. Unsafe directory creation: Your original command sudo mkdir $i tries to create a folder in the remote user's default working directory. If the hostname has special characters (like spaces), mkdir will treat them as separate arguments, or if the sudo user lacks permissions there, you'll hit issues.

Fixed Script

Here's the revised version with robust handling for hostnames and directory creation:

#!/usr/bin/ksh
# Read hostnames line-by-line to preserve spaces and skip empty lines
while IFS= read -r i
do
    # Skip any blank lines in the input file
    [[ -z "$i" ]] && continue
    
    # SSH to the host, create a folder named after the hostname in the sudo user's home directory
    # -p ensures parent folders are created (if needed) and avoids errors if the folder already exists
    ssh "$i" "sudo mkdir -p \"\$HOME/$i\""
done < "$1"

Key Improvements Explained

  • while IFS= read -r i: This reads each line of your hostnameList exactly as it is. IFS= preserves leading/trailing whitespace, and -r prevents backslashes in hostnames from being misinterpreted as escape characters.
  • Empty line check: [[ -z "$i" ]] && continue skips blank entries in your list, so we never try to SSH to an empty host or run mkdir without a target folder name.
  • mkdir -p: The -p flag makes mkdir create parent directories if they don't exist, and won't throw an error if the folder already exists—making the script more resilient.
  • Quoting the remote command: Wrapping the command in double quotes ensures it's passed correctly to the remote shell. \$HOME is escaped so the remote shell expands it to the sudo user's home directory, while $i uses your local loop variable (the hostname). Escaped double quotes around \$HOME/$i ensure the full path is treated as one argument, even if the hostname has spaces.

内容的提问来源于stack exchange,提问作者Stan K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:38:03