##!/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,预期结果如下:
#!/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
#!/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问题出在哪里?
发布于 2021-07-13 15:52:55
不要筑巢,巢,巢。相反,使用declare -f和函数将工作转移到不相关的上下文。
##!/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"在这种情况下,您可以检查运行脚本的用户是否是您想要的用户,然后使用该用户重新启动脚本:
##!/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用外壳检查检查您的脚本。
https://stackoverflow.com/questions/68365477
复制相似问题