linux - 命令替换在通过 SSH 传递的脚本文本中不起作用

标签 linux bash ssh ls

<分区>

我尝试使用以下 bash 访问文件夹的内容;

test_dir="/some_dir/dir_test"

ssh -t -t user@remote-host "
if [ -d '$test_dir' ]; then
    sudo chown -R user:admin '$test_dir'
    echo '$test_dir'/*
    if [ '$(ls -A $test_dir)' ]; then
        sudo rm -rf '$test_dir'/*
        echo '$test_dir'/*
fi"

脚本试图检查/some_dir/dir_test是否为空,如果不是,则删除该文件夹中的所有文件;但我收到以下错误;

ls: cannot access '/some_dir/dir_test': No such file or directory

/some_dir/dir_test
drwxr-xr-x.  3 sys admin   16 Sep 23 15:03 dir_test

但是,我可以sshremote-hostls -A/some_dir/dir_test

我想知道如何修复它。

最佳答案

$(ls -A $test_dir) 正在客户端本地执行,而不是服务器。您需要转义 $。您还需要在其周围使用 ",否则将不会执行命令替换。

    if [ \"\$(ls -A $test_dir)\" ]; then

通常执行多行命令的最佳方式是使用scp 将脚本复制到远程机器,然后使用ssh 来执行脚本。混合变量的本地和远程扩展以及命令替换变得复杂,尤其是当您需要引用它们时。

关于linux - 命令替换在通过 SSH 传递的脚本文本中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58066042/

相关文章:

bash - 向已在运行的进程提供参数(通过 bash 脚本)

c++ - 如何在不离开 X.11 环境的情况下开发 DirectFB 应用程序

linux - 在 bash 中设置全局变量

python - 使用 Python Blender 库编辑 STL 文件

bash - 如果在脚本中处理文件,如何保存文件名

visual-studio-code - 无法在 VSCode 上远程 SSH 到 Windows 主机

linux - Jenkins 和路径

linux - Bash shell 脚本。变量作为参数。无引号与双引号

python - SSH 权限被拒绝 : using paramiko module inside my flask app and deployed same using mod_wsgi(Apache) mode

执行命令后 PHP 脚本挂起