如何在bash字符串中放置通配符

时间:2015-04-09 19:41:18

标签: bash

我有一个目录USR/SRC/Code,因为每个人的使用都不一样,人们可以把它放在他们工作空间的任何地方我想做到这一点,只要SRC / Code在目录中可用像*/SRC/Code这样的工作是我尝试过但没有用过的东西:

#!/bin/bash

    DIRECTORY="/SRC/Code"
    if [ -d "\*$DIRECTORY" ]; then
        # Will enter here if $DIRECTORY exists, even if it contains spaces
            echo "TRUE"
    fi

#!/bin/bash

DIRECTORY="*/SRC/Code"
if [ -d "\$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists, even if it contains spaces
        echo "TRUE"
fi


#!/bin/bash

DIRECTORY="\*/SRC/Code"
if [ -d "\$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists, even if it contains spaces
        echo "TRUE"
fi

1 个答案:

答案 0 :(得分:2)

Globs可以匹配多个文件,因此最好将它们存储在一个数组中:

#!/bin/bash
shopt -s nullglob globstar    # Enable recursion and zero matching
directories=( **/SRC/Code )
case "${#directories[@]}" in
    1) echo "Found the directory: ${directories[0]}" ;;
    0) echo "There were no matches..." ;;
    *) echo "There was more than one match!" ;;
esac