it2check (2272B)
1 #!/bin/bash 2 # Make sure stdin and stdout are a tty. 3 if [ ! -t 0 ] ; then 4 exit 1 5 fi 6 if [ ! -t 1 ] ; then 7 exit 1 8 fi 9 10 # Read some bytes from stdin. Pass the number of bytes to read as the first argument. 11 function read_bytes() 12 { 13 numbytes=$1 14 dd bs=1 count=$numbytes 2>/dev/null 15 } 16 17 function read_dsr() { 18 # Reading response to DSR. 19 dsr="" 20 spam=$(read_bytes 2) 21 byte=$(read_bytes 1) 22 while [ "${byte}" != "n" ]; do 23 dsr=${dsr}${byte} 24 byte=$(read_bytes 1) 25 done 26 echo ${dsr} 27 } 28 29 # Extract the terminal name from DSR 1337 30 function terminal { 31 echo -n "$1" | sed -e 's/ .*//' 32 } 33 34 # Extract the version number from DSR 1337 35 function version { 36 echo -n "$1" | sed -e 's/.* //' 37 } 38 39 trap clean_up EXIT 40 _STTY=$(stty -g) ## Save current terminal setup 41 42 function clean_up() { 43 stty "$_STTY" ## Restore terminal settings 44 } 45 46 # Enter raw mode and turn off echo so the terminal and I can chat quietly. 47 stty -echo -icanon raw 48 49 # Support for the extension first appears in this version of iTerm2: 50 MIN_VERSION=2.9.20160304 51 if [ $# -eq 1 ]; then 52 MIN_VERSION=$1 53 fi 54 55 # Send iTerm2-proprietary code. Other terminals ought to ignore it (but are 56 # free to use it respectfully). The response won't start with a 0 so we can 57 # distinguish it from the response to DSR 5. It should contain the terminal's 58 # name followed by a space followed by its version number and be terminated 59 # with an n. 60 echo -n '[1337n' 61 62 # Report device status. Responds with esc [ 0 n. All terminals support this. We 63 # do this because if the terminal will not respond to iTerm2's custom escape 64 # sequence, we can still read from stdin without blocking indefinitely. 65 echo -n '[5n' 66 67 version_string=$(read_dsr) 68 if [ "${version_string}" != "0" -a "${version_string}" != "3" ]; then 69 # Already read DSR 1337. Read DSR 5 and throw it away. 70 dsr=$(read_dsr) 71 else 72 # Terminal didn't respond to the DSR 1337. The response we read is from DSR 5. 73 version_string="" 74 fi 75 76 # Extract the terminal name and version number from the response. 77 version=$(version "${version_string}") 78 term=$(terminal "${version_string}") 79 80 # Check if they match what we're looking for. This becomes the return code of the script. 81 test "$term" = ITERM2 -a \( "$version" \> "$MIN_VERSION" -o "$version" = "$MIN_VERSION" \)