首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在‘`su << <<EOF`’内‘`cat $user’EOF‘?

如何在‘`su << <<EOF`’内‘`cat $user’EOF‘?
EN

Stack Overflow用户
提问于 2021-07-13 15:38:23
回答 1查看 282关注 0票数 0
代码语言:javascript
复制
##!/bin/bash
set -e
backup_dir='/home/my/backup'
user='my'

su $user <<EOFHD
cat << 'EOF' > $backup_dir/autorestartnftables.sh
#!/bin/bash
SERVICENAME="nftables"

# return value is 0 if running
STATUS=$?
if [[ "$STATUS" -ne "0" ]]; then
        echo "Service '$SERVICENAME' is not curently running... Starting now..."
        systemctl start $SERVICENAME
fi
EOF
chmod +x $backup_dir/autorestartnftables.sh
EOFHD

上面的脚本用于创建autorestartnftables.sh,预期结果如下:

代码语言:javascript
复制
#!/bin/bash
SERVICENAME="nftables"
# return value is 0 if running
STATUS=$?
if [[ "$STATUS" -ne "0" ]]; then
        echo "Service '$SERVICENAME' is not curently running... Starting now..."
        systemctl start $SERVICENAME
fi

运行后的autorestartnftables.sh sudo bash ./example.sh

代码语言:javascript
复制
#!/bin/bash
SERVICENAME="nftables"
# return value is 0 if running
STATUS=0
if [[ "" -ne "0" ]]; then
        echo "Service '' is not curently running... Starting now..."
        systemctl start 
fi

问题出在哪里?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-13 15:52:55

不要筑巢,巢,巢。相反,使用declare -f和函数将工作转移到不相关的上下文。

代码语言:javascript
复制
##!/bin/bash
set -e
backup_dir='/home/my/backup'
user='my'
work() {
    cat << 'EOF' > $backup_dir/autorestartnftables.sh
#!/bin/bash
SERVICENAME="nftables"

# return value is 0 if running
STATUS=$?
if [[ "$STATUS" -ne "0" ]]; then
        echo "Service '$SERVICENAME' is not curently running... Starting now..."
        systemctl start $SERVICENAME
fi
EOF
    chmod +x $backup_dir/autorestartnftables.sh
}
su "$user" bash -c "$(declare -p backup_dir); $(declare -f work); work"

在这种情况下,您可以检查运行脚本的用户是否是您想要的用户,然后使用该用户重新启动脚本:

代码语言:javascript
复制
##!/bin/bash
set -e
backup_dir='/home/my/backup'
user='my'
if [[ "$USER" != "$user" ]]; then
   # restart yourself as that user
   exec sudo -u "$user" "$0" "$@"
fi

cat << 'EOF' > $backup_dir/autorestartnftables.sh
#!/bin/bash
SERVICENAME="nftables"

# return value is 0 if running
STATUS=$?
if [[ "$STATUS" -ne "0" ]]; then
        echo "Service '$SERVICENAME' is not curently running... Starting now..."
        systemctl start $SERVICENAME
fi
EOF
chmod +x $backup_dir/autorestartnftables.sh

用外壳检查检查您的脚本。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68365477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档