如果远程机器上已经存在文件,如何更改文件名? [英] How to change name of file if already present on remote machine?

查看:45
本文介绍了如果远程机器上已经存在文件,如何更改文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果某个文件已通过 SSH 存在于远程服务器上,我想更改该文件的名称.

I want to change the name of a file if it is already present on a remote server via SSH.

我从这里尝试了这个(超级用户)

bash
ssh user@localhost -p 2222 'test -f /absolute/path/to/file' && echo 'YES' || echo 'NO'

这适用于提示,文件存在时回显 YES,不存在时回显 NO.但我希望它从 crontab 启动,然后它必须在脚本中.

This works well with a prompt, echoes YES when the file exists and NO when it doesn't. But I want this to be launched from a crontab, then it must be in a script.

假设文件名为 data.csv,在循环中设置一个条件,例如如果服务器上已经有一个 data.csv 文件,则文件将重命名为data_1.csv,然后是data_2.csv,...直到名称唯一.

Let's assume the file is called data.csv, a condition is set in a loop such as if there already is a data.csv file on the server, the file will be renamed data_1.csv and then data_2.csv, ... until the name is unique.

重命名部分有效,但检测部分无效:

The renaming part works, but the detection part doesn't :

while [[ $fileIsPresent!='false' ]]
do
    ((appended+=1))
    newFileName=${fileName}_${appended}.csv

    remoteFilePathname=${remoteFolder}${newFileName}

    ssh pi@localhost -p 2222 'test -f $remoteFilePathname' && fileIsPresent='true' || fileIsPresent='false'
done

始终为任何 data_X.csv 返回 fileIsPresent='true'.所有路径都是绝对路径.

always returns fileIsPresent='true' for any data_X.csv. All the paths are absolute.

你有什么想法可以帮助我吗?

Do you have any idea to help me?

推荐答案

当你寻求帮助你的想法时,我认为值得一提的是,你可能不想启动多达 100 个 ssh 处理每个登录到远程机器的人,所以你可能会用这样的结构做得更好,它只建立一个运行直到完成的 ssh 会话:

As you asked for ideas to help you, I thought it worth mentioning that you probably don't want to start up to 100 ssh processes each one logging into the remote machine, so you might do better with a construct like this that only establishes a single ssh session that runs till complete:

ssh USER@REMOTE <<'EOF'
for ((i=0;i<10;i++)) ; do
  echo $i
done
EOF


或者,您可以在本地创建和测试 bash 脚本,然后像这样远程运行它:


Alternatively, you can create and test a bash script locally and then run it remotely like this:

ssh USER@REMOTE 'bash -s' < LocallyTestedScript.bash 

这篇关于如果远程机器上已经存在文件,如何更改文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆