11 ms·
Bringing the Unix philosophy to the 21st century (2019)
- richardanaya 5y agoI was literally just thinking about this a few days ago. I'm super excited by https://www.nushell.sh/ https://www.nushell.sh/ . I think they are hitting on an order of magnitude improvement paradigm of shells that fit very nicely with the theme of this article.
- sonofajojo 5y agoThis reminds me of powershell
- bassman9000 5y agohttps://www.nushell.sh/book/ https://www.nushell.sh/book/ This goes against the philosophy explicitly mentioned in OP's article. E.g. avoid tabular formats. This is systemd against init again. A powerful, but overreaching shell that becomes unreplaceable and bloated with concerns. In constrast, traditional *nix/GNU programs work well, and interact well, in every shell.
- selfhoster11 5y agoYou see traditional Unix/GNU programs as working well and interacting will. I see a programming paradigm designed for six-char identifiers, not designed for whitespaces and punctuation in names, running in something that emulates a physical terminal that emulated a paper-based terminal. Terseness is there, but ergonomics of use for non-utter-experts could be improved. I think that the shell paradigm could be so much better. If there's a momentum to make a change from that, I'll jump on the bandwagon. Any change is better than the current state of the shell.
- lakecresva 5y agoNushell has a 'to json' command. The tables are just nice to look at, it's not a data format they're expecting people to parse.
- bluecatswim 5y agoI've always been looking for anushell.
- zokier 5y ago> (iii) [...] Don't hesitate to throw away clumsy parts and rebuild them. Some forgotten wisdom right there.
- natt941 5y agoI can understand why the idea of more structured, object-like input and output is appealing, but after using PowerShell for a while, my take is that it's much harder to manipulate objects into a consistent format than it is to manipulate text. For instance, if you want to compare Azure DNS records with DNS records from a Windows server, it's a huge pain because Get-AzDnsRecordSet and Get-DnsServerResourceRecord return objects with different structures. Same problem if you want to pipe output of one util to another which expects slightly different format of input. More generally, text is great for loose coupling; structured objects, less so.
- zozbot234 5y ago> More generally, text is great for loose coupling; structured objects, less so. I disagree. Parsing "loose coupled" text and converting it to the format that a different tool expects is a rather non-trivial problem, and one that's often poorly specified to begin with; converting structured outputs is generally straightforward in comparison.
- guenthert 5y agoSure, converting (or interpreting) structured data is easier then unstructured. I doubt anyone is arguing that. I interpret op's statement however in that unstructured data is easier to couple unrelated tools. Tools perhaps which haven't written yet, by teams not knowing of each other and hence are unable to agree on a structure.
- kbrazil 5y agoI feel like if that were true then you’d have the majority of REST APIs delivering unstructured output instead of structured JSON, XML, CSV, etc. The market has spoken - there is true utility in structured text output.
- zamadatix 5y agoI think that's why the article proposes adding command line options and alternative APIs to output JSON objects not forcing all things the use objects all the time. For any serious data retrieving or scripting the light object wrapping will be superior. For quick one off use maybe the plain text option will be quicker to reason about.
- deleted 5y ago[deleted]
- seppoonbi3 5y agoI have noticed that people intuitively use unix philosophy _inside_ their programs. Not often you see well written software with functions that do not respect the unix philosophy (if only they would be programs and not functions).
- dan-robertson 5y agoEmacs is in many ways anti-Unix-philosophy and I think the way it’s software tends to be structured is no exception. Functions can get ad-hoc extensions or modifications all over the place with advice and hooks and dynamic scoping[1]. The only similarity is that in Unix most things are files and in Emacs most things are buffers. [1] Unix has weird ad-hoc mechanisms too like environment variables or your PATH containing modified versions of programs, and it has programs that do a thousand and one things, but I claim those are mostly violations of the Unix philosophy.
- zozbot234 5y agoThe Unix philosophy includes the use of software libraries in one's programs, albeit only resorted to when truly necessary. That often involves resorting to many of these tricks, usually for the sake of greater software reuse.
- pjmlp 5y agoA philosophy that is cargo cult, as it was hardly ever followed on commercial UNIX systems.
- tyingq 5y agoI agree that they handle some amount of unix philosophy intuitively. But, for example, lots of command line programs don't handle SIGPIPE.
- deleted 5y ago[deleted]
- jwilk 5y agoFWIW, "ip -j route" should work correctly since v4.17: https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/commit/?id=663c3cb23103f4e3 https://git.kernel.org/pub/scm/network/iproute2/iproute2.git...
- antonios 5y agoFreeBSD has started supporting JSON output for various tools via `libxo` in their base system for quite some time now.
- Koshkin 5y agoApparently, Plan9 has failed in this regard. What went wrong?
- pjmlp 5y agoI guess the team moved on to Inferno, plus this kind of shells don't play well with UNIX related culture. Xerox PARC workstations and Lisp Machines already solved the problem via their REPLs.
- ape4 5y agoThat `jc` command that converts non-json output to json is neat. But, um, seems slightly kludgy to be obvious. What if the `ifconfig` format changes slightly. I suppose its a stop-gap until all commands have a json output option.
- hjek 5y agoTrue. When I try it with `date` on Debian Sid I get parser error: $ jc -p date jc: Error - date parser could not parse the input data. Did you use the correct parser? For details use the -d or -dd option.
- kbrazil 5y agoOdd. What locale are you using? Should work fine with C or en_UTF8, per the readme.
- hjek 5y ago$ echo $LANG en_DK.UTF-8 $ date 2021-08-23T08:07:02 CEST
- kbrazil 5y agoAh, yes - that locale is not supported. From the Caveats section: For best results set the LANG locale environment variable to `C` or `en_US.UTF-8`. For example, either by setting directly on the command-line: $ LANG=C date | jc --date It is possible to add support for more locales and you can always override the built in parsers with your own plugin to support it.
- hjek 5y agoYea, however this means that @ape4's point still stands: > But, um, seems slightly kludgy to be obvious. What if the `ifconfig` format changes slightly.
- c0l0 5y agoSo I've been writing shell scripts for about two decades, about 75% of that time professionally. Parsing the unstructured, text-based output of utilities is not the problem for anyone who's had maybe a few weeks of training. Most `... | grep ... | cut ... | sed ... | awk ...`-abominations the post laments can be replaced by a single informed call to `awk`, making everything a lot more elegant and concise. Having JSON as an intermediate representation to work on instead is not going to save anyone - what we'd really need is for all tool versions/variants output on all platforms (all GNU/Linux distros, all the BSDs, all embedded Linux variants, all commercial UNICES, etc.) to be the same, all the time. That's not going to happen, so shell scripting is going to stay messy. Also, for my INTERACTIVE shell, anyone can try to pry free-form, text-based and semi-structured output from my cold, dead hands. JSON or YAML output might be an acceptable compromise between being easy to parse and bearable for human consumption, but for my daily work, I would rather have my tools make it easy for me, the human part in the whole equation, and not some parsing logic that might not even (need to) exist. Shell scripting provides most of its value from the fact that since I'm in its repl-of-sorts all the time, I can translate that familiarity to scripts and executables effortlessly, and I would not want that going away. But I am rather certain it would, if we had JSON (or another form of more structured data interchange syntax) adopted as the "universal" interface between UNIX tools.
- kbrazil 5y agoI don’t think the issue is that it’s hard to manually parse. The problem is that it’s hard for someone else to read your ad-hoc parser years later and reason about what you did if they need to modify it. Disclaimer: I am the author of the article and JC.
- pdimitar 5y agoThis is even more true for the ungodly long `jq` incantations that people write. It's like I get it, the old way is ugly and not always easy to decipher but at least it's shorter and your chances of understanding it are better. I've had both -- the classic piped chain of UNIX commands and various JSON-producing tools piped to `jq`. The former were still easier to work with.
- xrayarx 5y agoArticle from 2019 basically advertises https://github.com/kellyjonbrazil/jc https://github.com/kellyjonbrazil/jc which converts output of many unix cli commands into json, depends on Python
- eadmund 5y agoWhy not go all the way and use a format capable of expressing code and data? I refer, of course, to S-expressions. They also have the benefit of properly handling numbers. Some might look at the absence of maps as a negative, but I think alists are preferable anyway due to their constant ordering.
- kbrazil 5y agoThat’s a good debate to have. I settled on JSON due to its readability and ubiquity in web APIs. It’s something people all the way down and up the stack are very familiar with these days.
- eadmund 5y agoTrue, folks are very familiar with JSON, but it does have problems, and the best time to pick the best solution is before one has to deprecate a lesser solution. Computing is built atop a pile of decisions which made sense at the time and cannot be changed now due to compatibility (spaces in Makefiles, anyone?): there is no time like the present to simply choose to do the most correct thing. 'But folks won't use it!' Well, they might not. But if one gives folks a choice between the capability they need using an unfamiliar technology and not having the capability at all, they will learn the unfamiliar tech.
- selfhoster11 5y agoI'd rather avoid mixing the two. Shell injection is already a danger.
- lfnoise 5y agoYes. I never understood why JSON over s-exprs. The absence of maps is not a negative. S-exprs can represent maps. There are no maps in JSON, really anyway. It is just text. How that data is represented in memory is the output of parsing. You could just as well parse (dict (a 1)(b 2)(c 3)) into a hash table if you wanted. You could also have sets (set 1 2 3) or whatever other data structure.
- 5y ago
- freshhawk 5y agoUh ... what about when I don't want to load the entire stream into memory before the next stage starts running? Are these implicit json arrays that stream out? Or do we now have incompatible json shell tools and streaming text tools as a permanent fixture? I'm excited about structured output ideas, but json? I'd much rather have streams of whitespace separated words than json. That's in that "No type system is better than a bad type system" metaphorical area. I'll take grepping with a theoretically brittle regex over this jq[1] any day of the week. [1] jq -nc --stream 'inputs | select(length==2) | select( [.[0][0,2,4]] == ["results", "data", "row"]) | [ .[0][6], .[1]] '
- selfhoster11 5y agoFor the first point, there's no reason why we can't use JSON array wrapped output. In fact, we likely should use something like this for uniformity. Loading everything into memory is also not too problematic assuming a working swap space and reasonably well-architectured output schema. For the second point, whitespace sensitivity is the one mistake that greatly pisses me off with Unix. I should be able to pass arguments and filenames with as many spaces as I want. We are in the 21st century and occasionally do use spaces in filenames.
- kbrazil 5y agoI agree JSON is probably not right for every type of program output, but the age of web APIs has shown us that is probably great or adequate 90% of the time. If something is spewing out long lines of data I think JSON Lines would be a good option so you don’t need to read the whole structure into RAM. But any other structured output that has a healthy community and ecosystem supporting it would be better than just space delimited lines, or worse - groups of lines you need to deal with.
- woodruffw 5y agoI agree with you in broad strokes, but as a piece of anecdata: I've had a lot of success building tools that emit and consume JSONL[1] instead of entire JSON documents. JSONL preserves the Unix pipeline's inherently parallel design (people tend to forget this, even when waxing about the Unix philosophy!) but gives us all of the nice typing of a JSON stream. That being said, I too will take a `sed` or `awk` one-liner over some of the `jq` monstrosities that I've seen. [1]: https://jsonlines.org/ https://jsonlines.org/
- davidzweig 5y agoRelated, I am wondering if somebody is aware of a project to wrap cli utilies in a minimal 'TUI', along the lines of this: https://github.com/chriskiehl/Gooey https://github.com/chriskiehl/Gooey , but staying in the terminal. You'd pass the name of the program to run as the first argument. Haven't thought this through fully. EDIT: well, some discussion about this: https://github.com/chriskiehl/Gooey/issues/296 https://github.com/chriskiehl/Gooey/issues/296
- maple3142 5y agoParsing ad-hoc text formats always seem very fragile, as single spacr character (or even newline character) could easily break the pipeline. Using a proper data structure could make scripts works more "properly" when encountering these edge cases. Which format to use a as representation of data structure might be debatable, but I think JSON is a reasonable choice. (Formatted) JSON is readable by human and could be easily parsed by programs.
- rurban 5y agoThankfully he didn't propose XML. Unfortunately it looks like he (and many others) really thinks that JSON is better, even if it's underspecified, thus leading to possible insecurities. See the recent jsonsec thread. (Undefined key ordering and duplicate handling) So I have to bring in jsmn.h to parse protocols? Sorry no. Been there, done that. We are pushing too much unnecessary JSON around already. Unix is also about KISS. Structured data are lines and paragraphs.
- mcswell 5y agoWhile you're at it, bring Unix into the 21st century, in which we use Unicode (UTF-8 encoding). The number of Unix utilities that badly support Unicode is, well, painful to those of us who deal with non-ASCII data all the time.
- 10000truths 5y agoWhich utilities don’t support UTF8? I’ve never had encoding issues when using coreutil binaries e.g. grep or sed or awk. I guess if you want to display emojis or something, that might not work properly, but that’s an issue with your terminal, not with the utility you’re running.
- anthk 5y agoUnix "2.0" (plan9) invented utf-8.
- jrm4 5y agoSo, this is not "bringing it to the 21st century." I feel like what would actually do that is related to the idea of don't try to succeed perfectly, try to fail elegantly? I want some sort of non-destructive way for "the shell" to take a best guess at what's going on when I make a typo, or when the data's not formatted quite right, like a live linter that's there all the time.
- phendrenad2 5y ago"Up until about 2013 it made just as much sense as anything to assume unstructured text was a good way to output data at the command line..." But in 2013 a certain data format called JSON was standardized as ECMA-404..." "Had JSON been around when I was born in the 1970’s Ken Thompson and Dennis Ritchie may very well have embraced it as a recommended output format to help programs “do one thing well” in a pipeline." This whole post hinges on the theory that JSON is a revolutionary technology that no one had created something like before, and no one even considered creating before. But that seems completely wrong, right? "The Xerox Network Systems Courier technology in the early 1980s influenced the first widely adopted standard. Sun Microsystems published the External Data Representation (XDR) in 1987. XDR is an open format, and standardized as STD 67 (RFC 4506)" https://en.wikipedia.org/wiki/Serialization https://en.wikipedia.org/wiki/Serialization
- kbrazil 5y agoI don’t follow. Your examples are of data formats standardized in the 80’s while Unix was developed in the 60’s and 70’s. JSON even existed before 2013, but the fact that it became a standard in addition to being popular is the point I was making.
- sennight 5y agoI've spent a lot of time reverse engineering long dead hardware (and forgotten protocols), which means I've also spent a lot of time reading ancient papers generated by IBM, Bell, Arpa (so many long gone DoD programs), etc. So I sometimes have a hard time distinguishing between what is common knowledge and what is something that only myself and maybe a handful of others care about... That said, you know that every potential variation of every possible approach to accomplish what I presume your objectives are has already been exhaustively explored, documented, implemented, and finally abandoned by organizations with functionally limitless resources (aka open ended government contracts) - 50 years ago? Have you considered leveraging some of that work? I don't think many people know about the massive amount of work already done - that was just abandoned for a variety of reasons: reasons that often no longer apply, and very rarely have anything to do with the technology's utility. For example: everybody here knows about the OSI model and how sparsely filled out it is - but did you know that there is a layer set aside to do exactly what you are talking about, and that it just isn't being used? Thats right, #6, the presentation layer - specifically the virtual terminal protocol: which is where the designers wanted the object exchange and structured data to go... not in a mess of json one layer up. The VTP was outlined in several papers going back to at least '72. You could also lean on the Airforce's work for your data model, they ran that to ground pretty thoroughly with IDEF. You've also got a huge amount of free work from IBM when it comes to structured documents, and architecture that lends itself to semantic reasoning. Anyway, my larger point is that instead of exasperating the issue of wastefully bloated software teetering on increasingly high layers of abstractions (do a stack trace and consider the insanity of it), maybe the way to really improve our circumstances has already been discovered and then lost for a time. It would be no more difficult than trying to make kornshell-json a thing. A Survey of Terminal Protocols (1979) DOI 10.1016/0376-5075(79)90001-1 Computer Network Architectures and Protocols (1983) DOI 10.1007/978-1-4615-6698-4 IDEF: https://en.wikipedia.org/wiki/IDEF https://en.wikipedia.org/wiki/IDEF IBM's various journals (pre-'00) are also worth reading.
- dleslie 5y agoJSON is a terrible intermediary format since its structure is incompatible with streaming data; and demands full structure parsing before consuming the data.
- zaik 5y agoThe input and output of jq are JSON streams: > jq filters run on a stream of JSON data. The input to jq is parsed as a sequence of whitespace-separated JSON values which are passed through the provided filter one at a time. The output(s) of the filter are written to standard out, again as a sequence of whitespace-separated JSON data. https://stedolan.github.io/jq/manual/#Invokingjq https://stedolan.github.io/jq/manual/#Invokingjq
- yyyk 5y agoThe idea is good, but the approach cannot execute sufficiently. First, jc has to individually support each program and program mode, so improvements are bottlenecked on jc. Everytime you load a program you need to load all jc parsers. I also wonder how resistant the parsing is to surprises (filenames with bracket characters in ls output for example). Second, this does not handle interprogram piping (e.g. 'find . | xargs dosomething'). We have filtering to console but little piping (we can map the json output to a single column and pipe that, using the textual interface with all its deficiencies). To be clear, the author has no choice (rewriting all userland is a daunting concept), but a proper approach for 21th century Unix would be for all utilities to output and receive json (or whatever format is chosen) natively, and that the console would then be able to mange that into a textual format for the user.
- kumarsw 5y agoWith all the discussion here about object shells, it's a bit surprising that the project page doesn't make stronger emphasis that this (jc) is also a Python library that can take in the output of subprocess.Popen rather than fooling about with the mess that is jq. With that said, Python isn't especially nice for calling external programs. I can't wait for nushell/oil shell/elvish to hit maturity soon enough.
- cryptonector 5y agoHuh. I like that. jc.
- naveen99 5y agoStructured data people should prepare for a rude awakening from deep learning based tools. You can’t even regex into the working of a convolutional or recurrent neural network. The map will never be the territory.
- noisy_boy 5y agoIf I had to wish only one thing in context of shell scripts, it would be to be able to separate passing back the actual result from a function from stdout/stderr/logging without messing with boilerplate around non-standard file descriptors/named pipes/temp files etc.
- __MatrixMan__ 5y agoWhat, besides the actual result, do you write to stout? (And shouldn't it go to stderr instead?)
- noisy_boy 5y agoTypically informational messages/log message. Ideally yes logging should go to stderr but some applications that intercept the file descriptors consider anything to stderr as error and it is not always possible to change the handling for those applications. E.g. Octopus Deploy[0] does this: it doesn't outright fail the step assuming other "successful" steps happen after that but if the last command writes to stderr, it would; I use explicit exit statements as a workaround to handle this. [0]: https://octopus.com/ https://octopus.com/
- __MatrixMan__ 5y agoI guess I just wanted to be on a high horse and declare that anybody who puts something other than what you asked for on stdout is doing it WRONG. But you're right, fixing the universe to fit the convention isn't always in the cards. If I could design it all from scratch I'd have a convention for getting a program to tell me: - info, user prompts, debug -> stderr - foo data, bar data -> stdout That way I could use those defaults sometimes, but other times specify per-execution preferences that would route the data differently.
- noisy_boy 5y agoI was looking more into this and found something interesting[0]: > A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see Bash Builtins) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function. So something like below: set_var() { local -n vname=$1 # use nameref for indirection # some processing and assign value vname="abcd" } use_var() { local output set_var output # call function to populate the variable echo "output=$output" unset -n output } use_var I guess this is pretty close to "clean". Unfortunately, it is only available in bash 4.3, if I'm not wrong, so I don't have a choice to use it (our hosts use 4.2.x). [0]: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html https://www.gnu.org/software/bash/manual/html_node/Shell-Par...
- ilyash 5y agoThis is how you "integrate" `jc` with Next Generation Shell ( https://github.com/ngs-lang/ngs https://github.com/ngs-lang/ngs ): data = ``jc PROGRAM ARGS ...`` The double-backtick syntax runs the external program, `jc` in our case, and parses the output. It means that the "integration" is not `jc` specific. `data` is now structured data that comes from the parsed JSON. Example (run from your shell): ngs -pl '``jc ifconfig``.filter({"name": /docker/}).ipv4_addr' Will print IPs of all docker interfaces, one IP per line
- chalst 5y agoI'm more impressed by 12 Principles for a Diverging Desktop Future [dd] which is the vision for the Arcan project. [dd]: https://www.divergent-desktop.org/blog/2020/08/10/principles-overview/ https://www.divergent-desktop.org/blog/2020/08/10/principles...
- fargle 5y agowhy in the world would you pipe through grep to select certain lines and then use awk? You could just select lines with awk. The same could be said of cut. If you want to use grep and cut that's fine, but using grep and cut with awk implies you are doing it wrong. Cut for field 1 (`cut -d/` -f1) is a cheesy way of saying we want to delimit fields with '/' too. So add that to awk via script variable or via -F command-line option.
- kbrazil 5y agoIt's probably not the most correct, but it is a very common practice[0]. [0]https://stackoverflow.com/questions/23934425/parse-ifconfig-to-get-only-my-ip-address-using-bash https://stackoverflow.com/questions/23934425/parse-ifconfig-...