16

Im becoming desperate when debugging my script, I used some constructions recommended to me from my senior collegue and I dont know how to make it work properly.

 #!/bin/bash -x
set -ueo pipefail
exec &>/tmp/dq.log
source ${BASH_SOURCE%/*}/env-prd.sh

times=${2:-1}
sleep=${3:-1}

name="all-dq_hourly"


fs_lock_file="/tmp/mwa/jobs/prd-${name}.lock"

( flock -n 200
    log="/var/log/mwa/prd/$(date +%Y-%m-%d)__${name}.log"
    for i in $(seq 1 $times); do
        if [[ ! -f /tmp/stop ]]; then
        couple commands

      fi
        sleep $sleep
    done

) 200>"$fs_lock_file" | tee -a $log

rm $fs_lock_file

From the execs , I can see there is an issue with unbound variable for the tee -a $log part, couple commands get executed allright. I tried to use backtics in the log path, but to no benefit. I suspect the same issue with fs_lock_file, but I havent fixed the logging first yet.
Can somebody open my eyes and tell me what Im missing? Im not able to make the script logging to path specified.

1 Answer 1

9

You are assigning the variable log inside a subshell ( [...] ). That variable is not bound outside that subshell.

In this case it is probalby best to just set log outside the subshell, i.e. move the variable assignment before the subshell block.

Generally in similar cases, you could try replacing the subshell parentheses with curly braces (group command syntax) { [...] }.

Group commands are executed in the current shell. Note that in contrast to subshell syntax, lists must be terminated by newline or semicolon, see Compound Commands in the Lists section of the bash(1) manpage.

And as a general best practice, setting variable names, especially constants at the beginning of a script or function helps avoid this kind of bug.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you, moving it outside of the subshell solved the problem with unbound variable, however the script still doesnt log. It creates the empty logfile and doesnt write into it. Can I use the tee command the way I did or do I need to to add it to every command inside the subshell (about 20 of them)
Maybe your couple commands write to stderr only? Try redirecting that to stdout as well using 2>&1 before the | tee.
that was it, stdout produced nothing, the progress can be monitored via stderr, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.