如何通过Bash脚本复用单个Julia实例运行多个Julia脚本?
Perfect call focusing on eliminating Julia's startup overhead for consistent timing—this is a common pain point when running multiple scripts sequentially. The short answer: yes, you can absolutely do this entirely with shell scripting, using named pipes to keep a single Julia process alive and feed it your scripts one after another.
Here's a robust implementation that aligns with your goal, including support for real-time log monitoring with tail -f:
Step-by-Step Bash Script
#!/bin/bash # Clean up pipe and Julia process on exit (handles interrupts like Ctrl+C) cleanup() { echo "exit()" > julia_pipe 2>/dev/null wait $JULIA_PID 2>/dev/null rm -f julia_pipe exit } trap cleanup EXIT INT TERM # Create a named pipe to send commands to the persistent Julia process mkfifo julia_pipe # Start a single Julia process in interactive mode, reading from the pipe # Output is logged to submission.log, and we capture the process ID julia < julia_pipe 2>&1 | tee submission.log & JULIA_PID=$! # Helper function to run a Julia script in the persistent process run_julia_script() { # Send an `include()` command to Julia via the pipe echo "include(\"$1\")" > julia_pipe # Optional small delay to avoid race conditions between script runs sleep 0.1 } # Run your scripts sequentially in the same Julia process run_julia_script temp.jl run_julia_script j1.jl run_julia_script j2.jl run_julia_script j3.jl # Trigger cleanup (terminates Julia and removes the pipe) cleanup
How This Works
- Named Pipe (
julia_pipe): Acts as a reusable communication channel between your bash script and the persistent Julia process. Unlike anonymous pipes, it lets you send multiple commands over time instead of a one-time stream. - Persistent Julia Process: We start Julia in interactive mode (the default when no script is specified), so it stays alive waiting for input. Each
include("script.jl")command tells it to run your script in the same process—no startup overhead after the first run. - Logging & Real-Time Monitoring: The
tee submission.logcaptures all Julia output (stdout + stderr) into a log file. You can runtail -f submission.login another terminal to watch output as scripts execute. - Cleanup Trap: Ensures the Julia process is terminated and the pipe is deleted if you interrupt the script, preventing leftover processes or files cluttering your workspace.
Why This Beats a Master Julia Script
You explicitly wanted to avoid wrapping all scripts in a single Julia file—and this delivers: each script runs independently in the same process, so you don’t have to refactor your code, and timing for j1.jl, j2.jl, etc., won’t be skewed by Julia’s initial startup time.
内容的提问来源于stack exchange,提问作者Tims

