'is a directory' error when trying to pass directory name into function

Quotes and command substitution are your issues here.

The specific issue you're running into is because the shell is trying to run a command called /home/me/my_directory with the environment variable stuff=doStuff.
What you really want (if I'm interpreting correctly) is to run doStuff with the value of $i as an argument, assigning the output to the variable stuff. The way to do this is to wrap your command in $(). For example:

stuff="$(doStuff "$i")"

Notice How I also put quotes around everything. This is to prevent the shell from word splitting things you don't want it to word split (it'll turn a single argument of /foo/bar baz into /foo/bar and baz).

Also the output of your function is what gets used as the return value, not return.

As you should be using more quotes, you should also add them to everything else. Here is a complete version of your script:

doStuff() {
  echo "${1}" >&2
  printf '%s/hello' "$1";
}

IFS=$'\n'
for i in $(find "${directory}" -mindepth 1 -type d -name "${wildcard}");
do
  stuff="$(doStuff "${i}")"
done

You have to put the function definition before you try and use it. Shell isn't parsed like compiled programs, where it goes through the file several times. It's top-down.
I've also modified doStuff to send the echo to STDERR where it will be shown on the terminal, and then the printf sends to STDOUT where it will be captured into the variable stuff.

Note that this will still have an issue if any of your directories contains a newline. However this is a limitation of the shell. The only character a file path cannot contain is a NULL char (\0). However bash and other shells cannot store a NULL char in a string (not all, but many. I know zsh can), so you can't use it as a delimiter.


That is a good effort but it shows that you are trying to write bash as if it were a programming language, when it is actually a simple scripting language. The problem with your stuff=doStuff arg construction is that to bash it does not mean what you think it means. To bash, stuff=doStuff is a variable assignment, and arg is a command. I suggest you read the following two links:

  • How can I store the return value and/or output of a command in a variable?
  • How do I return a string (or large number, or negative number) from a function? "return" only lets me give a number from 0 to 255.

A working version of something similar to what you have would be

doStuff () {
    echo "$1/hello"
}

stuff=$(doStuff "$i")