Home > database >  Is it possible to create a file that when read, it runs a command to generate output?
Is it possible to create a file that when read, it runs a command to generate output?

Time:07-20

I'd like to create a file, for example lets call it /tmp/not_running_pods, that when read cat /tmp/not_running_pods runs kubectl get pods -o wide | grep -v Running and gives the output to the reading process.

This use case is simplified for example's sake. Not really looking for alternatives, unless it fits this exact case: file that outputs without having a 'service' always running listening for readers

Having a hard time finding anything specific for this on searching. My local env is macos, but hoping for something generalizable to linux/bash/zsh

edit: finally found what was on the tip of my brain, something like inetd / super-server - still looking to see if this would work for this case

CodePudding user response:

when read cat /tmp/not_running_pods runs

A file is static. It exists.

HTTP web servers runs a php script (and much more stuff) to generate the web page for you to view. An SSHD server runs a shell for you to connect with. MYSQL server serves a specific protocol that allows to execute queries. To "do something" when a connection is made typically sockets - network, tcp, but also file sockets - are used, that allow with accept() detect incoming connections and run actually an action on such event.

# in one terminal
$ f() { echo new >&2; echo Hello world; LC_ALL=C date; }; export -f f; socat UNIX-LISTEN:/tmp/file,fork SYSTEM:'bash -c f'
new
new

# in the second terminal
$ socat UNIX-CONNECT:/tmp/file -
Hello world
Tue Jul 19 21:29:03 CEST 2022
$ socat UNIX-CONNECT:/tmp/file -
Hello world
Tue Jul 19 21:29:19 CEST 2022

If you really want to "execute an action when reading from a file", then you have to create your own file system that does that. Primary examples are files in /proc /sys. For user space file systems, write a program using FUSE.

CodePudding user response:

Instead of

$ cat /tmp/not_running_pods

just make ~/bin/not_running_pods:

#! /bin/bash
kubectl get pods -o wide | grep -v Running

with chmod 755 and do

$ not_running_pods

Easy, well-understood, well-supported.

  • Related