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

Shell脚本新手求助:如何在远程查询脚本中添加cat命令

How to Add 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:

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 \$2 and \$file so the remote server interprets those variables, not your local shell.
  • Added read -r to handle file paths with spaces more safely.
  • The echo line 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 find command to use -print0 and xargs -0 to handle null-separated paths, but that's a small tweak if you run into that issue.

内容的提问来源于stack exchange,提问作者Andres L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:12:32