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:
- 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). - Unsafe directory creation: Your original command
sudo mkdir $itries to create a folder in the remote user's default working directory. If the hostname has special characters (like spaces),mkdirwill 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 yourhostnameListexactly as it is.IFS=preserves leading/trailing whitespace, and-rprevents backslashes in hostnames from being misinterpreted as escape characters.- Empty line check:
[[ -z "$i" ]] && continueskips blank entries in your list, so we never try to SSH to an empty host or runmkdirwithout a target folder name. mkdir -p: The-pflag makesmkdircreate 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.
\$HOMEis escaped so the remote shell expands it to the sudo user's home directory, while$iuses your local loop variable (the hostname). Escaped double quotes around\$HOME/$iensure the full path is treated as one argument, even if the hostname has spaces.
内容的提问来源于stack exchange,提问作者Stan K
相关产品推荐
相关产品推荐

