Detect if stdout is redirected to a pipe (not to a file, character device, terminal, or socket)?

后端 未结 5 895
粉色の甜心
粉色の甜心 2021-02-14 20:50

Ideally, this would be scriptable in shell, but Perl or Python would be fine. C code could be helpful, but probably fails cost/benefit.

I recognize that redirection to a

5条回答
  •  悲&欢浪女
    2021-02-14 21:33

    The stat command works on MacOS X and (with some finessing of variant implementations) other Linux/Unix variants as well, so it is a solution for me:

    FORMOPT=
    TYPEFORM=
    stat() {
      if [ -z "$FORMOPT" ]; then
        if /usr/bin/stat --version >/dev/null 2>&1; then
          FORMOPT=--format
          TYPEFORM=%F
        else
          FORMOPT=-f
          TYPEFORM=%HT
        fi
      fi
      case $1 in
        type) FORMARG="$FORMOPT $TYPEFORM" ; shift ;;
      esac
      /usr/bin/stat -L $FORMARG "$@"
    }
    
    exec 9>&1
    case `stat type /dev/fd/9` in
      [Ff]ifo*) echo stdout is a pipe ;;
      *) echo stdout is not a pipe ;;
    esac
    

提交回复
热议问题