I have a small function in my .zshrc. It creates a command to search for and run an executable file, that may or may not exist, in the current directory, or a parent directory somewhere up the current path. I have the logic to find the executable, if it exists, however when I try to run it, I get the following error:

Using /Users/username/some/directory/executable_file

function_name:15: no such file or directory: /Users/username/some/directory/executable_file

Generated by the following code:

if [[ $current_path != / ]]
    echo "Using $current_path/executable_file"
    "$current_path/executable_file $@"

That path is however correct, as copy-and-pasting it, or running the function with sudo, works perfectly. I've tried running the function as current user with sudo -u in the script, but it still fails.

How can I run the executable script, the same as if the user had typed it in manually, or at least without sudo and a password?

  • 1
    is that exactly how you have the quoting around "$current_path/executable_file $@" ? It seems to me that it should be "$current_path/executable_file" "$@" – Jeff Schaller Nov 2 '18 at 15:48
  • That format was based on answers I found elsewhere online. That seems to have fixed it! Write up an answer and explain why this is correct, you solved it! – RedBassett Nov 2 '18 at 15:52
  • I used it to look for the problem. As you can see in my question, I'm trying to find an actual solution without sudo. – RedBassett Nov 2 '18 at 16:18

The quoting around this line:

"$current_path/executable_file $@"

tells the shell that there's one item to be found and executed -- whatever is between the double-quotes (after the various variable expansions).

In the simplest case, with no parameters to your function, it will attempt to execute:

"$current_path/executable_file "

... which is probably failing, even if the $current_path/executable_file file itself exists, as there's a trailing space.

If you did happen to pass parameters, the likelihood is even lower that such a file exists, namely:

"$current_path/executable_file arg1 arg2 arg3..."

Rearrange the quotes so that you've protected the expansion of the $current_path variable, but allowed the executable's name to end when it should:

"$current_path/executable_file" "$@"
  • 1
    or just $current_path/executable_file "$@" as ZSH is free of those dangerous POSIX word splits (unless SH_WORD_SPLIT is turned on, but why ruin a good thing?) – thrig Nov 2 '18 at 16:11
  • 1
    I debated exploring that aspect of zsh, but opted for the known-safety of double-quoting for simplicity. Thank you for pointing out that zsh feature, though! – Jeff Schaller Nov 2 '18 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.