Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active January 11, 2022 11:52
Show Gist options
  • Save kou1okada/1ea8bfcd27968c9c93d5f9be58ddb1df to your computer and use it in GitHub Desktop.
Save kou1okada/1ea8bfcd27968c9c93d5f9be58ddb1df to your computer and use it in GitHub Desktop.
ttystate - Determine tty state

ttystate - Determine tty state

Example

$ ./ttystate.bash 0
tty
$ ./ttystate.bash 0 <ttystate.bash
redirect
$ echo | ./ttystate.bash 0
pipe
#!/usr/bin/env bash
# ttystate
# Copyright (c) 2019 Koichi OKADA. All rights reserved.
# This script is distributed under the MIT license.
#
function ttystate () # <var> <fd>
# Get tty state.
# Parameters:
# <var> : Variable name for return value
# <fd> : Number of file descriptor
# Return:
# Return tty, redirect or pipe to <var>.
{
local -n VAR="$1"
local STD=( /dev/stdin /dev/stdout /dev/stderr )
local T P
[ -t $2 ]; T=$?
[ -p ${STD[$2]} ]; P=$?
case "$T$P" in
01) VAR=tty ;;
11) VAR=redirect ;;
10) VAR=pipe ;;
*) echo "Error: unknown ttystate: $T$P"; exit 1 ;;
esac
}
if [ "$(readlink -f -- "$0")" = "$(readlink -f -- "$BASH_SOURCE")" ]; then
ttystate STATE "$1"
echo $STATE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment