【问题标题】:Unix Bash Shell Programming if directory existsUnix Bash Shell 编程(如果目录存在)
【发布时间】:2013-09-29 06:15:34
【问题描述】:

所以我试图进入 bash shell 脚本中的 if 语句,但我认为我做错了什么,无论如何这是我的示例代码。

#!/bin/bash
read sd
if [ -d "~/tmp/$sd" ]; then
    echo "That directory exists"
else
    echo "That directory doesn't exists"
fi
;;

我是否将其指向正确的目录?我希望用户输入将放入“sd”的内容,如果该子目录存在,那么它会说它存在,如果不存在,那么它会转到 else 并说它不存在。

【问题讨论】:

  • 波浪号没有在引号中展开。

标签: linux bash shell unix


【解决方案1】:

试试:

if [ -d ~/tmp/"$sd" ]; then

或:

if [ -d "$HOME/tmp/$sd" ]; then

引用可防止将~ 扩展到您的主目录。

【讨论】:

  • 感谢工作!现在假设有一个远程目录,我将如何找到该远程文件夹的确切目录?
  • 我不明白这个问题。您的代码没有找到任何内容,它获取目录名称作为输入。
  • 现在目录指向我个人计算机上的 /tmp 对吗?假设我需要连接一台远程计算机以检查那里是否存在目录,我将如何在远程位置找到 /tmp?我将如何检查远程位置是否存在“-d”目录?
  • 除非您使用 NFS、SSHFS、FTPFS 或类似的方式挂载了远程目录,否则您无法使用普通的 shell 函数访问它。您需要使用网络客户端应用程序,例如 ftpcurl
  • 您可以尝试这样的方法来检查远程服务器上是否存在目录:- if [[ ssh user@example.com test -d /path/to/my/directory && echo exists ]] ; then # put code in here fi
【解决方案2】:

试试这个:-

#!/bin/bash
read sd
if [ -d ~/tmp/"$sd" ]; then
    echo "That directory exists"
else
    echo "That directory doesn't exists"
fi

【讨论】:

  • 你为什么用;;最后?
  • @AhmedMasud:- 更新了。刚刚从 OP 的问题中复制!!
  • 谢谢!这正是它。现在有意义
  • @AhmedMasud 我用过 ;;最后,因为那是用于开关盒的东西?那是对的吗?我只是按照我被告知的去做。我没有使用我的整个代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 2013-10-21
  • 2011-11-21
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
相关资源
最近更新 更多