user122072
user122072

Reputation: 91

bash function - why doesn't it work

I have been trying to get this to work for a while now, and I am still confused as to why it doesnt work. I'm trying to add a function to my bashrc to cd down to the next directory that has files or more than one directory in it. But I cant get this test for files to work, and I do not understand the problem. find . -maxdepth 1 -type f works when I type it into the terminal, but here it doesn't seem to be working. And -z should test if it is null, which it should be when Icall it in an empty directory. But it just returns files detected every time... is it the use of the dot operator in doFilesExist?

function cdwn(){
    # check if there are files or multiple directories in current wd
    doFilesExist="find . -maxdepth 1 -type f"
    if [ -z '$doFilesExist' ]; then
        echo "no files  detected"
    else
        echo "files detected"
    fi
}

Thanks guys, seems to be working with the following:

function cdwn(){
    # check if there are files or multiple directories in current wd
    doFilesExist=`find . -maxdepth 1 -type f`
    if [ -z "$doFilesExist" ]; then
        echo "no files  detected"
    else
        echo "files detected"
    fi
}

But I am not satisfied as I do not understand why I was having problem, can you suggest some guides I can follow to get a better understanding? I clearly have either forgotten or not understood things in the past!

Upvotes: 1

Views: 951

Answers (2)

ShellFish
ShellFish

Reputation: 4551

You should try the following:

function cdwn(){
    # check if there are files or multiple directories in current wd
    files=$(find . -maxdepth 1 -type f | wc -l)
    if [[ ${files} -gt 0 ]]; then
        echo "files detected"
    else
        echo "no files detected"
    fi
}

Don't check using -z as it checks if a variable is set or not, it says nothing about the size. Also you just stored a command as a string, it has never been executed. To execute it you could store the content in a variable like some of the other answers suggest but those variables could become incredible large.

Upvotes: 1

idobr
idobr

Reputation: 1647

Looks like wrong quotes. To put a result of bash command to a variable:

doFilesExist=$(find . -maxdepth 1 -type f)

or

doFilesExist=`find . -maxdepth 1 -type f`

The part with if block should be also changed to [ -z "$doFilesExist" ]: "Inside a single-quoted string nothing(!!!!) is interpreted, except the single-quote that closes the quoting" source.

Upvotes: 1

Related Questions