【问题标题】:see if a directory/file exists with spaces in the name查看名称中是否存在带有空格的目录/文件
【发布时间】:2015-05-11 17:46:08
【问题描述】:

我想检查路径是文件还是目录。我知道路径存在。只要路径中没有空格,下面的代码就可以工作。如何使它适用于带空格的名称?我目前有一个带有名称的文件,无法远程检查它是否存在。代码如下:

server=<serverip>
path="/var/lib/Fingerprint log.log"

if ssh root@$server test -d $path
then
    echo "Directory"
else
    echo "File"
fi

当我有一条带有空格的路径时,它会失败

测试:/var/lib/Fingerprint:需要二元运算符

如果路径是 /var/lib/Fingerprint log.log

【问题讨论】:

  • 引用你的变量。总是引用你的变量。
  • @EtanReisner 当评论提供足够的提示时,表明问题已解决的 SO 约定是什么?
  • @Dinesh 通常我会让人们告诉我写它作为答案。 =) 这个问题刚刚出现,以至于它觉得它不值得还有另一个答案,我(诚然)懒得去找一个好问题来标记它的重复。
  • 问题在于实际上并没有一个明显重复的问题,而是数百个问题都具有相同的答案。这是一个问题,OP 可以通过阅读bash 标签信息页面上的提示和建议来回答自己(不幸的是,对于不熟悉 Stack Overflow 的人来说,这并不容易找到)。

标签: linux bash ssh space test-command


【解决方案1】:

根据最上面的评论,您需要使用“${path}”而不是 $path。

【讨论】:

    【解决方案2】:
    path="/var/lib/Fingerprint log.log"
    ssh root@$server test -d $path
    

    简短的回答是你应该像这样运行 ssh:

    ssh root@$server test -d "'$path'"
    or
    ssh root@$server "test -d '$path'"
    

    双引号确保$path 变量在本地系统上被扩展,并且单引号被传递到远程系统。单引号确保$path 的值仍被视为远程系统上的单个命令行参数。

    这是由于 ssh 如何处理在其命令行上指定的远程命令。首先,它将所有相关的命令行参数连接成一个以空格分隔的字符串。然后它将该字符串发送到远程系统,在那里它作为 shell 命令运行。

    例如:

    $ dne='/var/does not exist'
    $ ssh localhost ls $dne
    ls: cannot access /var/does: No such file or directory
    ls: cannot access not: No such file or directory
    ls: cannot access exist: No such file or directory
    
    $ ssh localhost ls "$dne"
    ls: cannot access /var/does: No such file or directory
    ls: cannot access not: No such file or directory
    ls: cannot access exist: No such file or directory
    
    $ ssh localhost ls "'$dne'"
    ls: cannot access /var/does not exist: No such file or directory
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多