bashfunctionat-job

Use a bash function inside an 'at' job


The at command can be used to schedule jobs for future execution.

This sets up the environment before executing the command, to match that at the time of creating at 'at' job.

However, this does not seem to include bash functions defined in the environment. I have tried exporting a function using "export -f" but this does not show up in the environment created for the at job.

Does anyone know how I could get a function to run in the context of an 'at' job? I know I could convert to a proper command defined in a file, but I'm curious what exactly is stopping the function from being picked up in the environment.

Notably, if one does "export -f myfun" in the environment and then "export -p", the function does not appear in the environment. Is this a bash issue more than anything?

Bash version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)


Solution

  • The script (let's say script.sh) you run with at will be run by atd daemon, and is no more related to your current shell session.

    A workaround :

    at ... << EOF
    /bin/bash << INNER
    # Import functions from current session
    $(declare -f)
    # Run the script
    $(cat script.sh)
    INNER
    EOF