提问人:Bharat Goyal 提问时间:1/14/2023 更新时间:1/14/2023 访问量:77
使用 sudo bash <<变量中的 EOF
Using sudo bash << EOF from a variable
问:
我从变量使用 HEREDOC 时遇到问题。
我有这个脚本,效果很好。但我想根据 ISROOT 的值使其有条件。如果 ISROOT=0,则不应调用 sudo -i -u db2inst1 bash << EOF,如果 ISROOT=1,则应调用它。
#!/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
但是,我的要求仅在 ISROOT == 1 时使用sudo -i -u db2inst1 bash << EOF
所以我想做这样的事情——
#!/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
这不起作用并引发错误:
+ sudo -i -u db2inst1 bash ''\''<<' 'EOF'\'''
bash: '<<: No such file or directory
有人可以帮忙吗?
我试过把EOF和<<放在单引号里,但仍然不起作用。
答:
2赞
KamilCuk
1/14/2023
#1
sudo -i -u db2inst1 bash << EOF 仅在 ISROOT == 1 时
太好了,所以只运行 sudo。否则,只需运行 bash。
if ((ISROOT == 1)); then
cmd=(sudo -i -u db2inst1 bash)
else
cmd=(bash)
fi
"${cmd[@]}" << EOF
echo "In"
....
EOF
评论
if [ "$UID" -eq 0 ] || [ "$EUID" -eq 0 ]; then #has-root-privileges; fi