How to trick an application into thinking its stdout is a terminal, not a pipe

前端 未结 9 1481
梦如初夏
梦如初夏 2020-11-22 11:58

I\'m trying to do the opposite of \"Detect if stdin is a terminal or pipe?\".

I\'m running an application that\'s changing its output format because it detects a pip

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 12:20

    Updating @A-Ron's answer to a) work on both Linux & MacOs b) propagate status code indirectly (since MacOs script does not support it)

    faketty () {
      # Create a temporary file for storing the status code
      tmp=$(mktemp)
    
      # Ensure it worked or fail with status 99
      [ "$tmp" ] || return 99
    
      # Produce a script that runs the command provided to faketty as
      # arguments and stores the status code in the temporary file
      cmd="$(printf '%q ' "$@")"'; echo $? > '$tmp
    
      # Run the script through /bin/sh with fake tty
      if [ "$(uname)" = "Darwin" ]; then
        # MacOS
        script -Fq /dev/null /bin/sh -c "$cmd"
      else
        script -qfc "/bin/sh -c $(printf "%q " "$cmd")" /dev/null
      fi
    
      # Ensure that the status code was written to the temporary file or
      # fail with status 99
      [ -s $tmp ] || return 99
    
      # Collect the status code from the temporary file
      err=$(cat $tmp)
    
      # Remove the temporary file
      rm -f $tmp
    
      # Return the status code
      return $err
    }
    

    Examples:

    $ faketty false ; echo $?
    1
    
    $ faketty echo '$HOME' ; echo $?
    $HOME
    0
    
    embedded_example () {
      faketty perl -e 'sleep(5); print "Hello  world\n"; exit(3);' > LOGFILE 2>&1 

提交回复
热议问题