Home > Software engineering >  Using sudo bash << EOF from a variable
Using sudo bash << EOF from a variable

Time:01-17

I have a issue when using HEREDOC from a variable.

I have this script which works fine. But I want to make it conditional based on value of ISROOT. If ISROOT=0 then sudo -i -u db2inst1 bash << EOF should not be called and if ISROOT=1 then it should be called.

#!/bin/bash
set -x
DBNAME="SAMPLE"
ISROOT=1
if [[ $ISROOT == 1 ]]; then
    DB2_PREFIX="sudo -i -u db2inst1 bash '<<' 'EOF' "
    DB2_POSTFIX=" 'EOF' "
  else
    DB2_PREFIX=" "
    DB2_POSTFIX=" "
  fi
  printf '\n\n%s\n\n' "Setting DB2_PREFIX: $DB2_PREFIX and DB2_POSTFIX: $DB2_POSTFIX"
  sleep 5

whoami

OUTPUTFILE=$( echo "XX.wlm.$( date " %Y%m%d_%H%M%S" )" )
{
sudo -i -u db2inst1 bash << EOF
echo "In"
whoami

db2 connect to $DBNAME
           db2 -v "call WLM_SET_CLIENT_INFO( null, null, null, null, 'SYSDEFAULTADMWORKLOAD' )"

           printf '\n\n%s\n\n' "Current state of queries"

           db2 -v "SELECT current timestamp as timestamp, ACTIVITY_STATE, SUM(ADM_BYPASSED) AS BYPASSED, COUNT(*) AS ACTIVE_CONNS FROM TABLE(MON_GET_ACTIVITY(NULL,-2)) AS T WHERE T.MEMBER = T.COORD_MEMBER GROUP BY ACTIVITY_STATE"

EOF
} 2>&1 | tee $OUTPUTFILE
echo "Out"
whoami

However my requirement is use sudo -i -u db2inst1 bash << EOF only when ISROOT == 1

So I want to do something like this -

#!/bin/bash
set -x
DBNAME="SAMPLE"
ISROOT=1
if [[ $ISROOT == 1 ]]; then
    DB2_PREFIX="sudo -i -u db2inst1 bash '<<' 'EOF' "
    DB2_POSTFIX=" 'EOF' "
  else
    DB2_PREFIX=" "
    DB2_POSTFIX=" "
  fi
  printf '\n\n%s\n\n' "Setting DB2_PREFIX: $DB2_PREFIX and DB2_POSTFIX: $DB2_POSTFIX"
  sleep 5

whoami

OUTPUTFILE=$( echo "XX.wlm.$( date " %Y%m%d_%H%M%S" )" )
{
$DB2_PREFIX
echo "In"
whoami

db2 connect to $DBNAME
           db2 -v "call WLM_SET_CLIENT_INFO( null, null, null, null, 'SYSDEFAULTADMWORKLOAD' )"

           printf '\n\n%s\n\n' "Current state of queries"

           db2 -v "SELECT current timestamp as timestamp, ACTIVITY_STATE, SUM(ADM_BYPASSED) AS BYPASSED, COUNT(*) AS ACTIVE_CONNS FROM TABLE(MON_GET_ACTIVITY(NULL,-2)) AS T WHERE T.MEMBER = T.COORD_MEMBER GROUP BY ACTIVITY_STATE"

$DB2_POSTFIX
} 2>&1 | tee $OUTPUTFILE
echo "Out"
whoami

This does not work and throws a error:


  sudo -i -u db2inst1 bash ''\''<<' 'EOF'\'''
bash: '<<: No such file or directory

Can someone please help.

I have tried putting EOF and << in single quotes but still does not work.

CodePudding user response:

sudo -i -u db2inst1 bash << EOF only when ISROOT == 1

Great, so run sudo only then. Otherwise just run bash.

if ((ISROOT == 1)); then
    cmd=(sudo -i -u db2inst1 bash)
else
    cmd=(bash)
fi
"${cmd[@]}"  << EOF
echo "In"
....
EOF
  • Related