Variable use within find command not working

Summary: I am trying to pass a variable from a function directly into a find command but it's not working

Long Story: I am currently writing a script to find the most recently updated directory in another directory and then run a command to deploy an app to a phone. I am basically trying to always find the newest update for my app and deploy it.

In Main, I define the base path (the part of the path that always stays the same) and my app name. I then call the FindNewestUpdate function and pass the basePath to it.

This function takes the path and returns the most recently updated directory inside that path (I got this neat command from another StackOverflow answer).

The last function takes this new path, steps inside it and deploys the app.

When I run this code, it doesn't work:

function Main {
    FindNewestUpdate "$basePath"
    DeployNewestUpdate "$finalPath" "$appName"

function FindNewestUpdate {
    mostRecentlyUpdatedDirectory=$(find $1 -type d -prune | tail -n 1)    
    echo $mostRecentlyUpdatedDirectory

function DeployNewestUpdate {
    cd $1    
    #deploy app with name $2


If I do this instead:

mostRecentlyUpdatedDirectory=$(find some/path/to/my/directory/* -type d -prune | tail -n 1)

it works perfectly. There has to be an error in how I am passing the $1 variable to the command.

I have tried constructing the entire command as a string first and I have tried numerous ways of escaping, none of them worked. But that might be linked to my inexperience.

I've read that it might have to do with how the shell works through the script. I.E. it runs the command before it expands the variable which might be why it can't run the command.

What confuses me is that when I run the script, the "echo $mostRecentlyUpdatedDirectory" prints the correct path and after that it exits with find: illegal option --t. Is there an explanation for that?

In the end it doesn't matter really but I would rather have that path be a variable than having it hardcoded. I am relatively new to shell scripting so I would appreciate any help.

(I am writing and executing this script on a Mac mini with macOS Mojave V10.14.3, but I don't think this is relevant, just adding it in case it is)

1 answer

  • answered 2019-08-15 12:52 Edvin

    FindNewestUpdate get called without an argument so it goes like find . -type d -prune | tail -n 1 what will search in the current working directory.

    FindNewestUpdate "$basePath" is what would give back the desired output but this output not used at all.

        FindNewestUpdate "$basePath"

    Solution would be

    finalPath=$(FindNewestUpdate "$basePath")