Heroku部署Jar生成config.txt后,如何让Shell脚本读取该文件?
Got it, let's break down how to make your shell script read that auto-generated config.txt file on Heroku. Here's a step-by-step approach that handles the timing of the Jar's startup and file creation:
1. Adjust Your Shell Script to Wait for config.txt
The key challenge here is that your Jar needs a moment to generate config.txt before the script can read it. We'll start the Jar in the background, wait for the file to exist, then extract the credentials.
Here's a complete start.sh script example:
#!/bin/bash # Launch your Jar in the background so the script can continue executing java -jar your-app.jar & # Capture the Jar's process ID to manage it later JAR_PID=$! # Wait for config.txt to be created (max 30 seconds - adjust as needed) MAX_WAIT_SECONDS=30 wait_counter=0 while [ ! -f config.txt ]; do sleep 1 wait_counter=$((wait_counter + 1)) # Exit with error if file never shows up if [ $wait_counter -ge $MAX_WAIT_SECONDS ]; then echo "Error: config.txt wasn't generated within $MAX_WAIT_SECONDS seconds" kill $JAR_PID exit 1 fi done # Extract username and password from config.txt # Adjust the grep patterns to match your config.txt's actual format # Example assumes lines like "username: my-random-user" or "password: my-secret-pass" USERNAME=$(grep -oP 'username: \K.*' config.txt) PASSWORD=$(grep -oP 'password: \K.*' config.txt) # Validate we actually got the credentials if [ -z "$USERNAME" ] || [ -z "$PASSWORD" ]; then echo "Error: Failed to pull username/password from config.txt" kill $JAR_PID exit 1 fi # Use the credentials however you need (log them, set env vars, etc.) echo "Successfully loaded credentials: Username=$USERNAME, Password=***" # Keep the script running (Heroku kills dynos without a foreground process) wait $JAR_PID
2. Key Details to Note
- Background Execution: Starting the Jar with
&lets the script proceed to the waiting step instead of blocking indefinitely. - Wait Logic: The loop ensures we don't try to read the file before it exists. Adjust
MAX_WAIT_SECONDSif your Jar takes longer to generate the file. - Credential Extraction: The
grep -oPcommand uses Perl-compatible regex to capture the value after the label. If yourconfig.txtuses a different format, tweak this part:- For
username=my-userformat:USERNAME=$(grep -oP 'username=\K.*' config.txt) - For JSON (you'll need to install
jqvia your buildpack first):USERNAME=$(jq -r '.username' config.txt)
- For
- Heroku Foreground Requirement: The final
wait $JAR_PIDkeeps the script running as a foreground process, which Heroku requires to keep your dyno alive.
3. Update Your Procfile
Make sure your Procfile points to the script, like:
web: ./start.sh
Just remember: Heroku's filesystem is ephemeral, so config.txt will be recreated every time your dyno restarts—but this script will handle that automatically each time.
内容的提问来源于stack exchange,提问作者lambad

