$ ./ttystate.bash 0
tty
$ ./ttystate.bash 0 <ttystate.bash
redirect
$ echo | ./ttystate.bash 0
pipe
Last active
January 11, 2022 11:52
-
-
Save kou1okada/1ea8bfcd27968c9c93d5f9be58ddb1df to your computer and use it in GitHub Desktop.
ttystate - Determine tty state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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