1

I have at the bottom of my .zshrc

[[ -e $HOME/.myapp/myapp.sh ]] && source $HOME/.myapp/myapp.sh

myapp.sh loads some environmental variables from a file called script_properties

{ [[ -e $HOME/.myapp/script_properties ]] && source $HOME/.myapp/script_properties; } || {printf "Please run setup script to set build configuration defaults.\n" && exit; }

and then checks a directory (lt_shell_functions_dir) where there are some bash scripts that I want to load as zsh functions. My hope is to be able to from the command prompt do something like "ltbuild", which is the name of a bash script that I want to run as a function. When I run "autoload ltbuild" from a zsh command prompt, it loads the file as a function (because it is in my fpath) and I can run it. When I try to load this from inside a script that executes on startup, so that I don't have to type "autoload ltbuild" it doesn't work. I appreciate the help!

if [[ -d $lt_shell_functions_dir ]]; then 
  fpath=($lt_shell_functions_dir $fpath)
  for function_file in $lt_shell_functions_dir/* 
  do
    autoload $function_file || printf "Autoloading $function_file failed\n"         
  done
  unset function_file
else
  printf "no $lt_shell_functions_dir exists.\n"
fi

Example:

I have a file named echome that has in it:

echo "I'm a file running as a function"

When I start a shell:

[carl@desktop[ 3:06PM]:carl] echome 
zsh: command not found: echome
[carl@desktop[ 3:06PM]:carl] autoload echome
[carl@desktop[ 3:07PM]:carl] echome
I'm a file running as a function
user1244166
  • 109
  • 1
  • 7

1 Answers1

0

Should note: I had no idea why this wasn't printing "autoloading failed", even after perusing man zshbuiltins. Luckily, zsh has a good community if you're ever stuck (both mailing lists and IRC) - they're worth using. From their explanation:

This isn't working because you're not autoloading the function correctly. What you're doing is autoloading a function called, for example, /path/to/lt_shell_functions/echome. What you want to be doing is autoloading a function called echome.

Note: Slashes / are allowed in function names. If you try to autoload a function that has not been defined, zsh will mark the function for loading later -- which is why it's not printing "autoloading failed" for you.

My solution: We can extract the name of the function like this:

${function_file##/*}

so I'd modify your ~/.zshrc to do this:

autoload ${function_file##/*} || printf "Autoloading $function_file failed\n"

which works:

Last login: Fri Jun 21 17:21:26 on ttys000
$ tail -n 12 ~/.zshrc
if [[ -d $lt_shell_functions_dir ]]; then
    fpath=($lt_shell_functions_dir $fpath)
    for function_file in $lt_shell_functions_dir/*
    do
        autoload -Uz ${function_file##*/} || printf "Autoloading $function_file failed\n"
    done
#    unset function_file
else
    printf "no $lt_shell_functions_dir exists.\n"
fi
$ echome
I'm in a file
Community
  • 1
  • 1
simont
  • 68,704
  • 18
  • 117
  • 136