Linux Unix Bash Shell 编程(如果目录存在)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19075074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:57:17  来源:igfitidea点击:

Unix Bash Shell Programming if directory exists

linuxbashshellunix

提问by user2318083

So I'm trying to get into an if statement in a bash shell script but I think I'm doing something wrong, anyways here's my sample code.

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

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

Am I pointing it to the correct directory? I want the user to input something which will be put into "sd" and if that subdirectory exists then it'll say it does, if not then it will go to the else and say it doesn't exist.

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

采纳答案by Barmar

Try:

尝试:

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

or:

或者:

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

Quoting prevents expansion of ~into your home directory.

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

回答by Rahul Tripathi

Try this:-

尝试这个:-

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