检查传入的参数是文件或目录的BASH [英] Check if passed argument is file or directory in BASH

查看:86
本文介绍了检查传入的参数是文件或目录的BASH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写在Ubuntu的一个极其简单的脚本,这将让我通过它不是一个文件名或目录,并能够做一些具体的,当它是一个文件,其他的东西当它是一个目录。我遇到的问题是目录名的时候,还是可能文件了,有空格或其他退避字符是在名称中。

I'm trying to write an extremely simple script in Ubuntu which would allow me to pass it either a filename or a directory, and be able to do something specific when it's a file, and something else when it's a directory. The problem I'm having is when the directory name, or probably files too, has spaces or other escapable characters are in the name.

下面是我的基本code楼下,一对夫妇的测试。

Here's my basic code down below, and a couple tests.

#!/bin/bash

PASSED=$1

if [ -d "${PASSED}" ] ; then
    echo "$PASSED is a directory";
else
    if [ -f "${PASSED}" ]; then
        echo "${PASSED} is a file";
    else
        echo "${PASSED} is not valid";
        exit 1
    fi
fi

和这里的输出:

andy@server~ $ ./scripts/testmove.sh /home/andy/
/home/andy/ is a directory

andy@server~ $ ./scripts/testmove.sh /home/andy/blah.txt
/home/andy/blah.txt is a file

andy@server~ $ ./scripts/testmove.sh /home/andy/blah\ with\ a\ space.txt
/home/andy/blah with a space.txt is not valid

andy@server~ $ ./scripts/testmove.sh /home/andy\ with\ a\ space/
/home/andy with a space/ is not valid

所有这些路径是有效的,并存在

All of those paths are valid, and exist.

推荐答案

这应该工作。我不知道为什么它的失败。你在正确引用您的变量。如果你使用这个脚本会发生什么双 [ ]]

That should work. I am not sure why it's failing. You're quoting your variables properly. What happens if you use this script with double [[ ]]?

if [[ -d $PASSED ]]; then
    echo "$PASSED is a directory"
elif [[ -f $PASSED ]]; then
    echo "$PASSED is a file"
else
    echo "$PASSED is not valid"
    exit 1
fi

双方括号中是一个bash扩展 [] 。它不需要变量被引用,甚至没有如果包含空格。

Double square brackets is a bash extension to [ ]. It doesn't require variables to be quoted, not even if they contain spaces.

另外值得一试: -e 来测试是否存在的路径没有测试它是什么类型的文件

Also worth trying: -e to test if a path exists without testing what type of file it is.

这篇关于检查传入的参数是文件或目录的BASH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆