简体   繁体   English

在bash shell脚本中检查目录的问题

[英]problems with checking for a directory in bash shell script

I am writing a batch-processing script bash that needs to first check to see if a folder exists to know whether or not to run a certain python script that will create and populate the folder. 我正在编写一个批处理脚本bash,需要首先检查是否存在一个文件夹,以了解是否运行某个将创建和填充该文件夹的python脚本。 I have done similar things before that do fine with changing the directories and finding directories from a stored variable, but for some reason I am just missing something here. 我之前做过类似的事情,可以更改目录并从存储的变量中查找目录,但出于某种原因,我只是在这里遗漏了一些东西。

Here is roughly how the script is working. 以下是脚本的工作原理。

if [ -d "$net_output" ]
then
    echo "directory exists"
else
    echo "directory does not exist"
fi

when I run this script, I usually echo $net_output in the line before to see what it will evaluate to. 当我运行这个脚本时,我通常在该行中回显$ net_output以查看它将评估的内容。 When the script runs I get my else block of code saying "Directory does not exist", but when I then copy and paste the $net_output directory path that is echoed before into the shell terminal, it changes directories just fine, proving that the directory does in fact exist. 当脚本运行时,我得到我的其他代码块说“目录不存在”,但是当我将之前回显的$ net_output目录路径复制并粘贴到shell终端时,它会更改目录就好了,证明该目录确实存在。 I am using Ubuntu 12.04 on a Dell machine. 我在戴尔机器上使用Ubuntu 12.04。

Thank you in advance for any help that someone can offer. 提前感谢您提供任何帮助。 Let me know what additional information I can provide. 让我知道我可以提供哪些其他信息。

The most common cases I've encountered when someone posts a problem like this are the following: 当有人发布这样的问题时我遇到的最常见的情况如下:

1. The variable contains literal quotes. 1.变量包含文字引号。 Bash does not recursively parse quotes, it only parses the "outer" quotes given on the command line. Bash不会递归地解析引号,它只解析命令行中给出的“外部”引号。

$ mkdir "/tmp/dir with spaces"
$ var='"/tmp/dir with spaces"'
$ echo "$var"
"/tmp/dir with spaces"
$ [ -d "/tmp/dir with spaces" ]; echo $?
0
$ [ -d "$var" ]; echo $?  # equivalent to [ -d '"/tmp/dir with spaces"' ]
1

2. The variable contains a relative path, and the current directory is not what you expected. 2.变量包含相对路径,当前目录不是您所期望的。 Check that the value of echo "$PWD" outputs what you expected. 检查echo "$PWD"的值是否输出您的预期。

3. The variable was read from a file with dos line endings, CRLF (\\r\\n). 3.从具有dos行结尾的文件CRLF(\\ r \\ n)读取变量。 Unix and unix-like systems use just LF (\\n) for line endings. Unix和unix类系统只使用LF(\\ n)作为行结尾。 If that's the case, the path will contain a CR (\\r) at the end. 如果是这种情况,路径将在末尾包含CR(\\ r)。 A CR at the end of a line will be "invisible" in a terminal. 一行末尾的CR将在终端中“不可见”。 Check with printf '%q\\n' "$var" while debugging the script. 在调试脚本时检查printf '%q\\n' "$var" See BashFAQ 52 on how to get rid of them. 请参阅BashFAQ 52 ,了解如何摆脱它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM