首页 > 解决方案 > Shell 脚本 - 如何在 if 语句中调用 python shell 命令

问题描述

我目前正在写我的 docker-entrypoint.sh 脚本。该脚本确定一个服务类型,它是一个环境。变量取决于返回的值,实际应用程序启动会有所不同。

在 if 语句中,我有几个命令来检查景观是否可以使用。我在这里也使用 Python,但总是遇到以下问题:

/usr/local/bin/docker-entrypoint.sh:第 128 行:警告:第 30 行的此处文档由文件结尾分隔(需要“EOF”)

/usr/local/bin/docker-entrypoint.sh:第 129 行:语法错误:文件意外结束

码头入口点.sh:

#!/usr/bin/env bash

############### App ###############

if [ "$SERVICE_TYPE" = "app" ]
then
  echo "I'm a Application instance, Hello World!"

  ...

  echo "Checking if System User is setup"
  {
  python manage.py shell <<-EOF
  from django.contrib.auth import get_user_model

  User = get_user_model()  # get the currently active user model
  User.objects.filter(user='$SYS_USER').exists() or User.objects.create_superuser('$SYS_USER', '$SYS_USER')
  EOF
  }

  ...

############### Celery Worker ###############

elif [ "$SERVICE_TYPE" = "celery-worker" ]
then
  echo "I'm a Celery Worker instance, Hello World!"

  ...

############### Celery Beat ##################

elif [ "$SERVICE_TYPE" = "celery-beat" ]
then
  echo "I'm a Celery Beat instance, Hello World!"
  ...


fi

如何在 if 语句中执行我的 python shell cmd,以便我基本上得到与如果我不会在这样的 if 语句中使用它的结果相同的结果:

echo "Checking if System User is setup"
{
cat <<EOF | python manage.py shell
from django.contrib.auth import get_user_model

User = get_user_model()  # get the currently active user model
User.objects.filter(user='$SYS_USER').exists() or User.objects.create_superuser('$SYS_USER', '$SYS_USER')
EOF
}

标签: pythonshelldockerentry-point

解决方案


Here-doc 结束标记不能有前导空格。此外,heredoc 中的脚本不应该有任何前导空格

#!/usr/bin/env bash

############### App ###############

if [ "$SERVICE_TYPE" = "app" ]
then
  echo "I'm a Application instance, Hello World!"

  echo "Checking if System User is setup"
  {
  python manage.py shell <<-EOF
from django.contrib.auth import get_user_model

User = get_user_model()  # get the currently active user model
User.objects.filter(user='$SYS_USER').exists() or User.objects.create_superuser('$SYS_USER', '$SYS_USER')
EOF
  }

############### Celery Worker ###############

elif [ "$SERVICE_TYPE" = "celery-worker" ]
then
  echo "I'm a Celery Worker instance, Hello World!"

############### Celery Beat ##################

elif [ "$SERVICE_TYPE" = "celery-beat" ]
then
  echo "I'm a Celery Beat instance, Hello World!"
fi

推荐阅读