mercredi 28 août 2019

BASH script error exits when variable is empty, but works when variable is set

I have the following bash code that is exiting when I enable "set -o errexit" and the variable in the code is empty, BUT works fine when the variable is set; the code is designed to test if a screen session matching ".monitor_*" exists, and if so do something.

I have the following turned on:

set -o errexit
set -x xtrace; PS4='$LINENO: '

If there is a sessions matching the above pattern it works; however, if nothing matches it just exits with no information other than the following output from xtrace

storage-rsync@nasro-prod01:~/scripts/tests> ./if_test.sh
+ ./if_test.sh
+ PS4='$LINENO: '
4: set -o errexit
5: set -o pipefail
6: set -o nounset
88: /usr/bin/ls -lR /var/run/uscreens/S-storage-rsync
88: grep '.monitor_*'
88: awk '{ print $9 }'
88: /usr/bin/grep -Ev 'total|uscreens'
8: ms=

I tested the command I am using to set the "ms" var and it agrees with the xtrace output, it's not set.

storage-rsync@nasro-prod01:~/scripts/tests> test -n "${mn}"
+ test -n ''

I have tried using a select statement and get the same results... I can't figure it out, anyone able to help? Thanks.

I read through all the possible solution recommendations, nothing seems to address my issue.

The code:

#!/usr/bin/env bash

set -o xtrace; PS4='$LINENO: '
set -o errexit
set -o pipefail
set -o nounset

ms="$(/usr/bin/ls -lR /var/run/uscreens/S-"${USER}" | /usr/bin/grep -Ev "total|uscreens" | grep ".monitor_*" | awk '{ print $9 }')"
        if [[ -z "${ms}" ]]; then
            clear; printf '\e[104m%-76s\e[0m\n\n' " START NEW MONITOR SESSION"
            read -r -p "ENTER NEW SCREEN SESSION NAME: " sname
            monitors="monitor_${sname}"
            /usr/bin/screen -S "${monitors}" -dm
            printf "\nSCREEN NAME : %s \n\n" "${monitors}"
            read -n 1 -s -r -p "Press any key to continue... "
            /usr/bin/screen -X -S "${monitors}" exec /usr/bin/env bash /mnt/storage_team/scripts/rsyncstatus/data/data.sh
            /usr/bin/screen -r "${monitors}"
        elif [[ -n "${ms}" ]]; then
            clear; printf '\e[104m%-76s\e[0m\n\n' " ATTACH TO ACTIVE MONITOR SESSION?"
            /usr/bin/ls -lR /var/run/uscreens/S-"${USER}" | /usr/bin/grep -Ev "total|uscreens" | grep ".monitor_*" | awk '{ print $9 }'; echo
            read -r -p "ENTER MONITOR'S SESSION NAME: " sname
            echo; read -n 1 -s -r -p "Press any key to attach... "
            /usr/bin/screen -r "${sname}"
        fi
exit

Aucun commentaire:

Enregistrer un commentaire