AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1873582
Accepted
mjbatty
mjbatty
Asked: 2025-01-28 23:13:41 +0800 CST2025-01-28 23:13:41 +0800 CST 2025-01-28 23:13:41 +0800 CST

Testar se um script está sendo executado dentro de outro script

  • 772

[ATUALIZAÇÃO] Obrigado pelos comentários e pensamentos até agora. Com base neles, atualizei e expandi a pergunta original com mais informações e exemplos.

Vamos supor que não haja nenhum caso de uso real por enquanto. O único objetivo é descobrir se isso é possível e, se for, como.

Quero executar um script e determinar se ele é executado diretamente pelo usuário ou chamado dentro de outro script. Também quero verificar se ele é originado ou não.

Isso significa que há 4 casos de teste principais:

  • executado no terminal, não originado
  • executar no terminal, originado
  • executar em script (não em terminal), não originado
  • executar em script (não em terminal), originado

Meu cérebro enferrujado, o Google e o ChatGPT me deram uma lista de verificações para testar se estavam sendo executadas em um terminal, mas nenhuma delas está dando resultados corretos em todas as 4 chamadas.

Os testes estão prontos check-terme há um script de chamada check-term-driver, ambos abaixo.

Se eu executar os 4 casos de teste na ordem dada acima, para que um determinado número de teste esteja correto (digamos, o número de teste n), quero que a saída seja:

n: in terminal:     not sourced: ...
n: in terminal:     sourced: ...
n: not in terminal: not sourced: ...
n: not in terminal: sourced: ...

O teste para saber se há ou não origem está correto em todas as 4 chamadas.

script de verificação de termo:

#!/usr/bin/env bash

IS_TERMINAL=true
NOT_TERMINAL=false
TEST_NUM=0
SOURCED_TEXT="undefined"

print_result() {
  TEST_NUM=$((TEST_NUM + 1))
  if [ "$1" = "$IS_TERMINAL" ]; then
    printf "%2d: %-16s %-12s %s\n" "$TEST_NUM" "in terminal:" "$SOURCED_TEXT:" "$2"
  else
    printf "%2d: %-16s %-12s %s\n" "$TEST_NUM" "not in terminal:" "$SOURCED_TEXT:" "$2"
  fi
}

# First check if script is sourced or not.
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  SOURCED_TEXT="not sourced"
else
  SOURCED_TEXT="sourced"
fi

# Tests run individually in expanded if/else for clarity.
# - test condition described by the result text.
if [ -t 0 ]; then
    print_result "$IS_TERMINAL" "stdin is a terminal"
else
    print_result "$NOT_TERMINAL" "stdin is not a terminal"
fi

if [ -t 1 ]; then
    print_result "$IS_TERMINAL" "stdout is a terminal"
else
    print_result "$NOT_TERMINAL" "stdout is not a terminal"
fi

if [ -t 2 ]; then
    print_result "$IS_TERMINAL" "stderr is a terminal"
else
    print_result "$NOT_TERMINAL" "stderr is not a terminal"
fi

if [[ "$-" == *i* ]]; then
    print_result "$IS_TERMINAL" "interactive shell"
else
    print_result "$NOT_TERMINAL" "non-interactive shell"
fi

if [ -n "$(tty)" ]; then
    print_result "$IS_TERMINAL" "has a controlling terminal"
else
    print_result "$NOT_TERMINAL" "does not have a controlling terminal"
fi

if [ -p /dev/stdin ]; then
    print_result "$NOT_TERMINAL" "running in a pipeline"
else
    print_result "$IS_TERMINAL" "not running in a pipeline"
fi

if [ -z "$(jobs -p)" ]; then
    print_result "$IS_TERMINAL" "running in foreground"
else
    print_result "$NOT_TERMINAL" "running in background"
fi

# Get ID of process that started the script.
PPID_VALUE=$(ps -o ppid= -p $$ | awk 'NR==2 {print $1}')

# If ID can't be found, give it a default value.
[ -z "$PPID_VALUE" ] && PPID_VALUE=1

# Check if attached or not.
if [ "$PPID_VALUE" -ne 1 ]; then
    print_result "$IS_TERMINAL" "attached to a parent process"
else
    print_result "$NOT_TERMINAL" "detached from a parent process"
fi

# Check if the parent process is a shell
PARENT_CMD=$(ps -o args= -p "$PPID_VALUE" 2>/dev/null)
if echo "$PARENT_CMD" | grep -qE '/(bash|zsh|sh)(\s|$)'; then
    print_result "$IS_TERMINAL" "parent process is a shell"
else
    print_result "$NOT_TERMINAL" "parent process is not a shell"
fi

Script do driver:

#!/usr/bin/env bash

./check-term
echo ""
. ./check-term
bash
  • 2 2 respostas
  • 184 Views

2 respostas

  • Voted
  1. Cyrus
    2025-01-30T02:41:19+08:002025-01-30T02:41:19+08:00

    Testado com bash versão 3.2.57, 4.4.18, 5.1.16 e 5.2:

    #!/bin/bash
    
    if [[ ${#BASH_LINENO[@]} -gt 1 ]]; then
      echo "sourced, script"
    else
      if [[ "$0" = "${BASH_SOURCE[0]}" ]]; then
        
        parent=$(ps -o comm= $PPID)
        if [[ "$parent" =~ "bash" ]]; then
          echo "not sourced, terminal"
        else
          echo "not sourced, script ($parent)"
        fi
    
      else
        if [[ "${BASH_REMATCH[0]}" != "bash" ]]; then
        echo "sourced, terminal"
        fi
      fi
    fi
    

    Nota 1: Este código não funciona corretamente se o bashbinário tiver sido renomeado e seu nome não contiver mais bash.

    Nota 2: Este código não funciona se for executado a partir de uma função.

    • 1
  2. Best Answer
    mjbatty
    2025-01-30T16:53:03+08:002025-01-30T16:53:03+08:00

    A maneira mais confiável de conseguir isso (até agora) é usar uma variável de ambiente, como sugerido por pai-to; isso funciona em todos os cenários, incluindo chamadas de funções aninhadas.

    A solução sugerida por Cyrus é independente (sem dependências externas), e eu a usaria se tivesse certeza de que o teste não seria usado em uma função.

    Embora a solução da variável de ambiente funcione, eu ainda preferiria uma sem dependências externas; se alguém tiver uma solução, por favor me avise.

    Aqui está uma demonstração funcional usando uma variável de ambiente.

    termo de verificação:

    #!/usr/bin/env bash
    
    IS_SOURCED=
    IN_SCRIPT=
    
    # Check if not sourced.
    if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
      IS_SOURCED=false
    else
      IS_SOURCED=true
    fi
    
    # Check if called by script.
    if [[ -n "$CT_CALLER" ]]; then
      IN_SCRIPT=true
    else
      IN_SCRIPT=false
    fi
    
    if [ "$IS_SOURCED" = false ] && [ "$IN_SCRIPT" = false ]; then
        echo "in terminal: not sourced"
    elif [ "$IS_SOURCED" = true ] && [ "$IN_SCRIPT" = false ]; then
        echo "in terminal: sourced"
    elif [ "$IS_SOURCED" = false ] && [ "$IN_SCRIPT" = true ]; then
        echo "in script: not sourced"
    elif [ "$IS_SOURCED" = true ] && [ "$IN_SCRIPT" = true ]; then
        echo "in script: sourced"
    else
        echo "Error: Invalid state"
    fi
    

    motorista:

    #!/usr/bin/env bash
    
    # Set calling script name"
    export CT_CALLER="ct-driver"
    
    ./ct-sea
    . ./ct-sea
    
    • 1

relate perguntas

  • substituindo zsh por bash no usuário não root

  • Tendo problemas para definir variáveis ​​de ambiente no Terminal no macOS High Sierra

  • Existe um equivalente a cd - para cp ou mv?

  • Notificar-enviar notificações aparecendo na janela

  • como abrir um arquivo de escritório do WSL

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como posso reduzir o consumo do processo `vmmem`?

    • 11 respostas
  • Marko Smith

    Baixar vídeo do Microsoft Stream

    • 4 respostas
  • Marko Smith

    O Google Chrome DevTools falhou ao analisar o SourceMap: chrome-extension

    • 6 respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Martin Hope
    Vickel O Firefox não permite mais colar no WhatsApp web? 2023-08-18 05:04:35 +0800 CST
  • Martin Hope
    Saaru Lindestøkke Por que os arquivos tar.xz são 15x menores ao usar a biblioteca tar do Python em comparação com o tar do macOS? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh Como posso reduzir o consumo do processo `vmmem`? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Pesquisa do Windows 10 não está carregando, mostrando janela em branco 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve