Search code examples
linuxbashgithub-actions

How can i run a command in the terminal and instead of logging in the terminal window, i redirect it to a file


i would like to write the log output of running a command in the terminal to a file. I want the log output to be saved despite of whether the command ran into an error or not. This should work for any command in the CLI (Iam using ubuntu-latest for github actions) some sample code in app.js

for(var i=0;i<5;i++){
 console.log(i);
}

The following command works well

nohup node node-app/src/app.js &> logs.txt

But when an error occurs (i am adding y to cause the error)

for(var i=0;i<5;i++){
 console.log(i*y); //here is an error
}

The above terminal command fails and the job ends with an exit code 1.

Here is my workflow

name: Send Job Logs to mail

on:
  push:
    branches:
      - main

jobs:
  send_email:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - id: logsData
      run: |
       nohup node node-app/src/app.js &> logs.txt
       cat logs.txt
       echo "logdata<<EOF" >> $GITHUB_ENV
       echo "$(tail -n +2 logs.txt)" >> $GITHUB_ENV
       echo "EOF" >> $GITHUB_ENV
       
    - name: Send log output to email
      uses: dawidd6/action-send-mail@v3
      with:
        server_address: smtp.gmail.com
        server_port: 25 
        username: ${{secrets.EMAIL_ADD}}
        password: ${{secrets.PSW_EMAIL}}
        from: john Delvin
        to: [email protected]
        subject: job-logs
        body: ${{env.logdata}}

Solution

  • As your use case requires you to run the rest of the commands in case there's a failure, you need to use something like this with OR (||) operator:

    nohup node node-app/src/app.js &> logs.txt || true
    

    This will return true if the command fails and the rest of the flow should run.

    Using continue-on-error: true makes the step pass but it stops execution right away and the rest of the flow is skipped.