Shell脚本新手求助:如何在远程查询脚本中添加cat命令
cat to Read Your Remote Files in the Script Hey there! Let's walk through how to modify your script to run cat on those matching files—you're almost there!
First, let's recap what your current script does: it reads a date, loops through directories in $Rec, connects to a remote server to find files modified in the last 10 days, filters for files matching your input date, and extracts their paths.
To add cat, we need to either run it directly on the remote server (more efficient) or fetch the file paths first and then run cat on each one. Here are two solid approaches:
Approach 1: Single SSH Connection (Recommended)
This method runs all logic on the remote server in one go, which saves you from multiple SSH connections. We'll wrap the entire remote command in quotes and add a loop to cat each matching file:
read date echo -e "RECORDINGS" for e in $Rec do sshpass -p password ssh user@server " # All commands here run directly on the remote server find $e -type f -mtime -10 -exec ls -gGh --full-time {} \; | cut -d ' ' -f 4,7 | grep $date | awk -F ' ' '{print \$2}' | while read -r file; do echo -e \"\\n=== Content of \$file ===\" cat \"\$file\" done " done
Key Notes for This Version:
- We escaped
\$in\$2and\$fileso the remote server interprets those variables, not your local shell. - Added
read -rto handle file paths with spaces more safely. - The
echoline adds a clear separator so you can tell which file's content you're looking at.
Approach 2: Fetch Paths First, Then cat
If you prefer to separate the "find files" and "read files" steps, you can store the remote file paths in a local variable first, then loop through them to run cat:
read date echo -e "RECORDINGS" for e in $Rec do # Grab the list of matching remote files remote_files=$(sshpass -p password ssh user@server "find $e -type f -mtime -10 -exec ls -gGh --full-time {} \;" | cut -d ' ' -f 4,7 | grep $date | awk -F " " '{print $2}') # Loop through each file and run cat remotely for file in $remote_files do echo -e "\n=== Content of $file ===" sshpass -p password ssh user@server "cat \"$file\"" done done
Heads-Up:
- Security Warning: Hardcoding your password in the script is risky. Consider setting up SSH key authentication instead of using
sshpass—it's safer and more convenient. - File Names with Spaces: If your remote files have spaces in their names, both approaches above might break. To fix this, you'd need to adjust the
findcommand to use-print0andxargs -0to handle null-separated paths, but that's a small tweak if you run into that issue.
内容的提问来源于stack exchange,提问作者Andres L

