diff options
author | Aaron Ball <nullspoon@iohq.net> | 2016-08-04 08:49:26 -0600 |
---|---|---|
committer | Aaron Ball <nullspoon@iohq.net> | 2016-08-04 08:49:26 -0600 |
commit | c3e907406ef05b1d74ac9be91db129daf89a717c (patch) | |
tree | d75810516392c4f526883086617b025d7df4c636 /src | |
parent | 4807d2e3c9fbfe76e27a4b6055b13a6392a9f6a5 (diff) | |
download | oper.io-c3e907406ef05b1d74ac9be91db129daf89a717c.tar.gz oper.io-c3e907406ef05b1d74ac9be91db129daf89a717c.tar.xz |
linux development:detecting output type
Finished bash section. Started writing section explaining how it works
using C.
Diffstat (limited to 'src')
-rw-r--r-- | src/linux_development:detecting_output_type.ascii | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/src/linux_development:detecting_output_type.ascii b/src/linux_development:detecting_output_type.ascii index 792ee3d..235bcae 100644 --- a/src/linux_development:detecting_output_type.ascii +++ b/src/linux_development:detecting_output_type.ascii @@ -68,10 +68,71 @@ ____ Let's give this a try. +.test.sh +---- +#!/usr/bin/env bash + +if [[ -t 1 ]]; then + echo -e "\e[32mYay! Colored text is cool!\e[0m" +else + echo -e "Boo! Plain text is lame." +fi +---- + + +If we execute this with './test.sh', we'll see the green colored text "Yay! +Colored text is cool!". +If we then execute this with './test.sh | less', we'll see the plain text "Boo, +Plain text is lame." This also outputs plain text if you redirect the output +using './test.sh > test.out'. +What -t Really Does +------------------- + +When I saw this functionality in bash, I immediately wanted to know how it +worked. Sure, I'd read the documentation, but there's no understanding like the +understanding that comes from writing it in C yourself. + + +---- +#include <stdio.h> +#include <sys/stat.h> + +/** + * Detects if the specified file descriptor is a character device, or something + * else. + * Useful for determiniing if colored output is supported. + * + * @param FILE* fd File descriptor to check + * + * @return int FD is char dev (1) or not (0) + */ +int ischardev(FILE* fd) { + struct stat d; + // stat the file descriptor + fstat(fileno(stdout), &d); + + // Check st_mode (see "man 2 stat" for more information about this) + if(S_ISCHR(d.st_mode)) + return 1; + + return 0; +} + +int main(int argc, char* argv[]) { + if(ischardev(stdout)) { + printf("Character dev. Colors supported\n"); + } else { + printf("Something else. Colors not supported\n"); + } + + return 0; +} +---- + :revdate: June 29, 2016 [role="datelastedit"] |