Shell cookbook
Start a script with #!/usr/bin/env sigil. The scripting prelude supplies commands, files, paths, text, time, iteration, and regex. See shell scripting for the complete command contract. The recipes below pair familiar Bash patterns with Sigil. External tools are still useful; structured arguments remove a layer of shell parsing.
retry is new in the source version accompanying this cookbook. On an older installed release, use an explicit bounded loop or update the interpreter. Libraries can import it from (sigil shell patterns); direct scripts get it from the prelude.
Commands and exact arguments
| Bash | Sigil |
|---|---|
git -C "$root" status --short | ($ git -C ,root status --short) |
printf '<%s>' "$value" | ($ printf "<%s>" ,value) |
printf '<%s>' "${items[@]}" | ($ printf "<%s>" ,@items) |
kill -0 "$pid" | ($? kill "-0" ,pid) |
git add -A -- . | ($ git add -A -- ".") |
Declare required tools before work begins:
(requires (tools git printf))
(define root (arg 1 default: "."))
($ git -C ,root status --short)Interpolation inserts one argument, including spaces and empty strings. There is no implicit glob expansion; use glob explicitly. Sigil still has reader traps: quote "-0", a lone "." (bare, it is dotted-pair syntax and the script fails to parse with "expected single element after dot"), leading-zero identifiers, digit-leading hashes, keywords used as literal arguments, and comma-containing strings such as "pid,etime,pcpu,args". Write a complete option as one string; adjacent bare tokens and strings are separate arguments.
Running a command with a child umask
The shell API does not yet expose a child-process umask option. When a test must compare actual process masks, keep its orchestration in Sigil and use this temporary shell fragment only to set the mask before exec:
($ sh -c "umask 0077; exec \"$@\"" sh ,binary ,@arguments)The fixed fragment receives the command and its arguments separately. Record this temporary scripting exception in the test's work notes.
Capturing large command output while cross-compiling
Use a synchronous capture with a deadline when the complete output fits in memory:
(define result ($? compiler --verbose timeout: 60))
(unless (ok? result)
(error (format-outcome result)))
(write-text "compiler.log" (stdout-of result))Capture uses the running host's process implementation even when SIGIL_FEATURES includes windows for a cross-compilation target. It drains stdout and stderr while feeding stdin on Unix and Windows, including output larger than a pipe buffer. Windows timeouts terminate the immediate child; Unix timeouts terminate the process group created for the command. For output that should go directly to disk, use spawn with file sinks and then wait; waiting on a child with undrained capture pipes can deadlock:
(define job (spawn compiler --verbose out: "compiler.log" err: "compiler.err"))
(define status (process-wait job))Use process-communicate-start when an event loop needs to stay responsive while a tool runs. Pass variable names to unset-environment: when they should be absent from the child, including when the parent needs to keep them.
(define child
(process-spawn "converter" "input.svg"
unset-environment: '("CONVERTER_DEBUG")
new-process-group: #t))
(define run (process-communicate-start child timeout: 20))
;; Call once per event-loop turn. #f means the child is still pending.
(process-communicate-poll run)The completed result contains the wait result, stdout and stderr bytevectors, and a timeout flag. To abandon a run, call process-communicate-cancel! and keep polling until the child is reaped.
For readable data files, (format "~s" value) preserves keywords inside lists and vectors, with the same spelling and string escapes as write. Read the resulting datum with read; use ~a for display text.
Buffered output
| Bash | Sigil |
|---|---|
printf 'Ready: %s\n' "$name" | (println "Ready: ~a" name) |
printf 'Progress: ' | (display "Progress: ") (flush-output-port) |
println and eprintln pass a complete formatted line to the port once, including the newline. POSIX stdout uses line buffering for terminals, files, and pipes, so each completed line appears immediately. For bulk output, set SIGIL_STDOUT_BUFFERING=block before starting Sigil to opt into block buffering. Windows stdout is unbuffered by default; Windows terminals remain unbuffered with the opt-in. Flush explicitly after a partial response, or a response in block mode, when the peer must receive it before the program continues:
(display response)
(newline)
(flush-output-port)Normal return, explicit exit, and an uncaught language error flush pending stdout. Starting a child flushes the parent's stdout first. Stdin reads flush partial stdout prompts when either stdin or stdout is a terminal, including stdout piped through tee. Every stderr write flushes preceding stdout so merged diagnostics retain their order. emergency-exit bypasses cleanup; an OS termination that cannot run cleanup cannot flush pending data either.
If a consumer closes stdout early, Sigil terminates quietly with SIGPIPE (status 141 in shells). A closed descriptor (EBADF, as with >&-) discards stdout quietly. Other errors (for example, ENOSPC from /dev/full) print a stderr diagnostic and exit with status 1, including failures on the final flush. POSIX startup reserves closed standard descriptors with /dev/null, so later file opens cannot receive discarded stdout. An exit-time stdout failure flushes other buffered files first. A closed pipe can replace explicit (exit 3) or an uncaught error's status with SIGPIPE. A consumer exiting before its input reaches EOF stops upstream stages whose output has not reached EOF. For example, (out (pipe (yes y) (head -n 1))) returns "y". The pump closes the producer's output pipe and allows SIGPIPE, then escalates to TERM and KILL within 250 ms if the producer stays alive. $? retains every stage outcome; finished stages keep their exit statuses, and producers stopped by this cleanup have closed-early? outcomes. A failed consumer still fails the pipeline. A producer that has reached normal output EOF can finish later work without cancellation, and its natural exit status remains part of the pipeline result. For child-side output redirection, use spawn with out:; synchronous $? captures output first and writes its file sink in the calling process.
Capture and exit status
| Bash | Sigil |
|---|---|
revision=$(git rev-parse HEAD) | (define revision (out git rev-parse HEAD)) |
mapfile -t files < <(git ls-files) | (define files (lines git ls-files)) |
if git diff --quiet; then ...; fi | (if (ok? ($? git diff --quiet)) ... ...) |
$ and captures require success. $? returns an outcome for the script to inspect. A failed command, a missing executable, a signal, and a timeout are different causes. Ignoring $? does not make the script fail automatically.
(define result ($? git diff --quiet))
(unless (ok? result)
(eprintln "~a" (format-outcome result)))out removes trailing CR/LF characters. Use (stdout-of ($? ... ansi: #t)) when those bytes matter, and inspect the outcome before using them. The default capture also strips ANSI escape sequences. Preserve them when parsing machine output such as Git's NUL-delimited tree names, since an escape sequence can be part of a real filename:
(define tree-result ($? git ls-tree -rz HEAD ansi: #t))
(unless (ok? tree-result) (error "Cannot read Git tree" (format-outcome tree-result)))
(define raw-tree (stdout-of tree-result))Pipelines
Bash:
set -o pipefail
producer | consumerSigil:
(define result ($? (pipe (producer) (consumer))))
(each stage (stage-outcomes result)
(unless (ok? stage) (eprintln "~a" (format-outcome stage))))
(unless (ok? result) (error "pipeline failed" result))Sigil retains each stage's outcome, including successful stages. An upstream producer closed by a successful consumer has a distinct closed-early cause. The current pipeline API has no deadline and does not retain separate captured stderr per stage. For a command that may hang, prefer a bounded synchronous command or manage explicit process handles until pipeline deadlines exist.
Lines and regular expressions
| Bash | Sigil |
|---|---|
grep -E '^v[0-9]+\.[0-9]+$' | (regex-match? "v[0-9]+\\.[0-9]+" value) |
sed 's/[[:space:]]\+/ /g' | (regex-replace-all "\\s+" text " ") |
while IFS= read -r line; do ...; done < file | call-with-input-file with read-line, below |
(call-with-input-file "events.log"
(lambda (port)
(let loop ()
(let ((line (read-line port)))
(unless (eof-object? line)
(when (starts-with? line "ERROR ") (println "~a" line))
(loop))))))Compile a reused pattern once with regex. Patterns use RE2-style syntax; lookaround and backreferences are rejected. Matching positions are Unicode character indexes. For large simple scans, grep can be much faster than a Sigil regex loop; the measured survey records that loss.
JSON
| Bash | Sigil | |
|---|---|---|
| `curl --fail --silent "$url" | jq .version` | (dict-ref (json curl --fail --silent ,url) version:) |
jq -n --arg version "$version" '{version:$version}' | (json-encode (dict version: version)) |
(import (sigil json))
(define document (json-decode (read-text "manifest.json")))
(define packages (dict-ref document packages:))
(each package packages
(println "~a" (dict-ref package name:)))Objects use keyword keys; JSON arrays are Sigil arrays. each accepts either arrays or lists. Encode strings with json-encode; concatenating quoted fields is unsafe when a value contains a quote, backslash, or newline.
Reading lists from a JSON API
Bash:
set -o pipefail
curl --fail --silent "$url" |
jq -r 'if has("result") and (.result | type) == "array"
then .result[] | .name
else error("missing or invalid result array") end'Sigil:
(import (sigil json))
(requires (tools curl))
(define url (arg 1))
(define response (json-decode (out curl --fail --silent ,url)))
(define raw (json-get-in response '(result:) 'missing-result))
(when (eq? raw 'missing-result)
(error "API response is missing result"))
(define zones (->list raw))
(each zone zones
(println "~a" (json-get-in zone '(name:))))json-get-in uses keyword keys for decoded objects. An API response with "result": [] is a valid empty collection: ->list returns '() and the loop runs zero times. A missing result returns the supplied sentinel and raises before the loop. A false, null, or object value also raises in ->list. This prevents an unexpected response from silently appearing to contain zero items. Outside the scripting prelude, import (sigil list) for ->list.
File trees, permissions, and links
| Bash | Sigil |
|---|---|
mkdir -p "$directory" | (ensure-directory directory) |
readlink "$link" | (read-symlink link) |
ln -s "$target" "$link" | (make-symlink target link) |
chmod 600 "$file" | (set-file-mode! file #o600) |
Import (sigil fs) for file-mode, set-file-mode!, and file-sha256 in source versions that provide them. To inspect a link itself rather than its target, use (file-stat file #f). directory-walk does not descend through symlinks by default. Decide whether following links is appropriate for the job; do not quietly change a legacy find -L traversal into a different policy.
Checksums and sidecars
Bash:
(cd "$directory" && sha256sum -- "$name" > "$name.sha256")Sigil:
(import (sigil fs))
(define digest (file-sha256 artifact))
(unless digest (error "could not hash artifact" artifact))
(write-text (str artifact ".sha256")
(str digest " " (basename artifact) "\n"))The sidecar names the artifact relative to its directory, so verification can run there. SHA256SUMS text conventions need extra escaping for filenames with newlines or backslashes; reject such names or use a structured manifest. For atomic publication, create a temporary file in the destination directory, write and close it, then rename it over the sidecar. Hash the final artifact, and fail if hashing returns #f.
For a toolchain repair, stage every replacement and check all expected hashes before publishing the first file. Keep the original files as backups, refuse unknown edits and symlinked installation directories, and hash the installed files again after rename. A version string or marker file alone cannot prove which SDK sources a compiler will use. The Zig libc integration checks in test/integration/check-zig-libc.sgl demonstrate a warm-cache repair and restoring individual source files to verify that stale libc objects are not reused.
Serialize repair writers with with-file-lock from (sigil fs), then rehash after acquiring the lock because another process may have finished first. Keep the lock pathname after use so waiting processes cannot lock different inodes. Patched sources can skip the writer path. Stage backups before renaming them to their permanent names, and use a fresh staging directory for each transaction: a killed writer may leave a partial stage that should neither block a later repair nor be trusted. The installed-CLI controls in test/integration/check-zig-libc-upgrade.sgl cover concurrent first builds, pristine reinstalls, and recovery between two source replacements.
A linked SDK root is a read-only addressing convenience only when its resolved target already has both patched hashes. Do not acquire a writer lock or repair through such a link. Preserve incomplete installations under a named backup before publishing a new verified tree, and remove only the private extraction stage on failure. Version activation should report optional SDK failures separately so users can still roll back the CLI.
HTTP with a deadline and retained evidence
To serve a folder locally, use (http-serve-directory "public" port: 8080) or sigil serve public --port 8080. Both bind to 127.0.0.1 by default; host:/--host selects another interface, and listing: #t/--listing opts into directory listings.
| Bash | Sigil |
|---|---|
curl --fail --max-time 5 "$url" | ($? curl --fail ,url timeout: 5) |
(define response ($? curl --silent --show-error --fail ,url timeout: 5))
(write-text "response.stdout" (stdout-of response))
(write-text "response.stderr" (stderr-of response))
(unless (ok? response) (error "HTTP command failed" response))The outcome keeps both streams even when the command times out. A transport success and a particular HTTP status are different assertions. Use curl's status output or an HTTP library when a non-2xx response is expected.
Polling and retry
Bash:
for attempt in 1 2 3; do
curl --fail --max-time 2 "$url" && break
sleep 1
doneSigil:
(define response
(retry (lambda () ($? curl --fail --silent ,url timeout: 2))
attempts: 3 delay: 0.2 factor: 2 max-delay: 1))
(unless (ok? response) (error "request exhausted retries" response))attempts: includes the first call. Success stops immediately; exhaustion returns the last outcome unchanged. Exceptions propagate, including an error raised by the optional on-retry: observer. Retry only operations whose repeated effects are acceptable. This is bounded backoff, not a transaction retry policy or an overall wall-clock deadline.
For readiness, use wait-until instead:
(wait-until (ok? ($? curl --fail --silent ,health-url timeout: 1))
timeout: 5 interval: 0.1 message: "service did not become ready")Bound each blocking predicate separately. The polling deadline is checked after an unsuccessful predicate; it cannot interrupt one that is blocked.
Cold compiler timing
For compiler timing, keep the driver's cache separate from the measured child's cache. Inherit an already assigned CPU affinity and niceness; adding another nice -n 10 in the child adds to the parent's priority adjustment.
(with-temp-dir cache
(let* ((started (current-jiffy))
(result ($? ,compiler -L ,sources eval --quiet ,expression
env: ,(list (cons "XDG_CACHE_HOME" cache)) timeout: 120)))
(println "seconds=~a status=~a"
(/ (- (current-jiffy) started) (jiffies-per-second)) (exit-status result))
(unless (ok? result) (error (format-outcome result)))))Repeat measurements and retain each result. Run builds before timing, and collect verbose diagnostics separately so their output cost is excluded.
Private mount namespace checks
For a mount-sensitive integration check, keep the controller in Sigil and reinvoke it inside unshare -U -r -m. Make propagation private before mounting a fresh tmpfs under a temporary directory, and run the operation under test in a child. A second user namespace locks inherited mount flags, which lets a test exercise read-only bind remounts on nosuid/nodev stores without changing host mounts. Bound both the namespace command and its children. See test/integration/test-external-mounts.sgl for a complete source-build check. Run its Make target with an explicit channel input: SIGIL_SANDBOX_TEST_CHANNEL=/path/to/channel make check-external-mounts. The channel must provide seed/seed-x86_64-linux.tar.gz.
When resolving a path's mount options, import (sigil io), open the path, and use port->fd with /proc/self/fdinfo/FD to obtain its mnt_id, then select that exact ID from /proc/self/mountinfo. Covered mounts remain listed, so textual mountpoint prefixes cannot establish which mount serves the path.
Background jobs and parallel work
| Bash | Sigil |
|---|---|
server >server.log 2>&1 & pid=$! | (define server (spawn server out: "server.log" err: 'merge)) |
wait "$pid" | (process-wait server) |
(import (sigil threads))
(define results
(parallel-map (lambda (file) (out sha256sum ,file)) files workers: 2))Thread closures must capture serializable values, not process handles or ports. Ordinary shell children belong to their parent's lifetime. Independent services require detached: #t and a log path; use that deliberately. Drain piped output with process-communicate, rather than waiting for a child whose full output pipe prevents it from exiting.
Bounded builds with private state
For build jobs, process handles are useful when each child needs its own writable tree, caches, and live log. Limit the number of active handles, poll them with process-alive?, and reap completed children with process-wait before starting queued work. A child-side file sink avoids output pipe deadlocks while the parent polls other jobs:
(define child
(spawn ,builder ,target
cwd: ,target-root
env: ,(list (cons "XDG_CACHE_HOME" (path target-root "cache")))
in: "/dev/null" out: ,(path target-root "build.log") err: 'merge))
;; During the pool's polling loop:
(unless (process-alive? child)
(let ((status (process-wait child)))
(unless (= status 0) (println "FAILED ~a: ~a" target status))))Do not hard-link writable build trees or dependency Git metadata. Git worktrees contain absolute links in both directions, so copying a worktree alone does not isolate its repository. Keep running queued jobs after a child fails, aggregate all failures with their log paths, and write aggregate release records only after every child succeeds. Keep previously qualified artifacts private until that point too. Resolve the interpreter to an absolute executable before spawning children with a different working directory. Also bound any compiler pool inside each child; otherwise an outer limit can multiply into many more processes. The repository's scripts/release-targets.sgl implements this complete pattern, including retained per-target state and an explicit serial mode (--jobs 1). Resource admission runs for automatic and requested limits alike: hold back two CPUs, reserve 5 GiB per worker plus 1 GiB memory headroom, and refuse a zero budget before creating target state. Explicit excess requires --force-jobs and prints a warning; it still cannot exceed the hard cap of eight.
Finding files across directory components
(each gitdir (glob "repos/*/*/*.git/worktrees/*/gitdir")
(println "~a: ~a" gitdir (read-text gitdir trim: #t)))
(define links (glob "deps/*/.git"))Since 0.24.4, relative and absolute patterns accept * in intermediate directory components and literal hidden components such as .git. * stays within one component; a complete ** component traverses zero or more directories without following directory symlinks. Wildcards skip hidden names unless their component explicitly starts with .. Results are files. Recursive results preserve directory-walk order, omit file symlinks, and contain each pathname once even when the pattern contains multiple ** components. Character classes, braces, ?, and wildcard escaping are unsupported. Older interpreters can return an empty list for these patterns despite existing matches. Use directory-walk and filter by type and basename when supporting those versions. That walk visits hidden directories.
Arguments and help
| Bash | Sigil |
|---|---|
action=${1:-status} | (define action (arg 1 default: "status")) |
arguments=("$@") | (define arguments (script-args)) |
An absent argument and an empty string are different values. arg preserves that distinction. For option definitions, validation, subcommands, and generated help, use (sigil args) rather than growing an ad hoc flag parser.
Temporary files and cleanup
Bash:
work=$(mktemp -d)
trap 'rm -rf "$work"' EXITSigil:
(with-temp-dir work
(write-text (path work "input") "example\n")
($ cat ,(path work "input")))The temporary tree is removed on normal return and exception unwinding without following symlinks. Use a retained evidence directory and explicit dynamic-wind cleanup for a failed harness whose logs must survive. Neither approach can clean up after an OS-level kill; an immediate exit also skips ordinary unwind cleanup.
Updating a directory while names may change
Import the anchored filesystem API explicitly. Its names are single basenames; open each child directory instead of passing a multi-component relative path:
(import (prefix (sigil fs anchored) anchored:)
(only (sigil fs) sync-file))
(anchored:call-with-directory "/var/lib/example"
(lambda (root)
(let ((child (anchored:open-directory-at root "records")))
(dynamic-wind
(lambda () #f)
(lambda ()
(let ((port (anchored:open-output-file-at child "new-unique" #o600)))
(dynamic-wind
(lambda () #f)
(lambda ()
(write-string "record\n" port)
(sync-file port))
(lambda () (close-output-port port))))
(anchored:rename-file-no-replace-at child "new-unique" child "published")
(anchored:sync-directory child))
(lambda () (anchored:close-directory child))))))The prefix distinguishes descriptor-based synchronization from the prelude's pathname-based sync-directory. The exclusive create and no-replace rename refuse existing names. The directory handle continues to address the opened inode if its pathname is replaced. Check directory-handle-stat against a parent's file-stat-at when detecting such replacement is part of the application policy. Unlink and replacing rename do not compare the current leaf with a preflight inode; serialize writers when that guarantee is needed. Linux is supported initially; other platforms refuse. See anchored filesystem operations for errors, durability, cleanup, and the full concurrency boundary.
Signals
Bash's trap cleanup INT TERM has no one-line scope equivalent. Sigil provides signal callbacks, but dispatch and process shutdown remain explicit:
(import (sigil signals))
(define stopping? #f)
(on-signal 'int (lambda () (set! stopping? #t)))
(on-signal 'term (lambda () (set! stopping? #t)))
(let loop ()
(check-signals!)
(unless stopping?
($? health-check timeout: 1)
(loop)))Callbacks are dispatched at scheduler polls or check-signals!; they do not turn a synchronous blocking operation into an interruptible one. Put owned child termination and reaping in cleanup, and check identity before signaling a process reconstructed from a stored PID.
TTY and PTY
Bash commands normally inherit terminal streams. Sigil command captures use pipes; a program that reads /dev/tty has a different requirement from one that reads stdin. For terminal emulation, use the lower-level PTY API:
(define terminal (process-spawn-pty program cols: 120 rows: 40))
(process-pty-write terminal "status\n")
;; Poll process-pty-read, which returns a bytevector or EOF.
;; An empty bytevector means no bytes are ready yet.
;; After draining and completing the protocol:
(process-pty-close! terminal)
(process-wait terminal)PTY output combines terminal streams and can include control sequences. It is not a replacement for separate stdout/stderr capture. This remains more verbose than invoking a terminal-oriented tool from Bash.
Binary output and live logs
Bash:
base64 --decode input.b64 > output.bin
compiler 2>&1 | tee build.logSigil can send binary output directly to a child-side file sink:
(define child (spawn base64 --decode "input.b64" out: "output.bin"))
(unless (= (process-wait child) 0) (error "decoder failed"))For synchronous text capture redirected to a file, ansi: #t prevents default ANSI processing from changing arbitrary bytes. Avoid out for binary payloads because it trims trailing newline bytes. The survey contains an executed non-UTF-8 example.
There is no single checked command form that both tees stdout and stderr live, retains them separately, and enforces an overall deadline. spawn file sinks make logs visible during execution; another reader can follow the file. A pipeline through tee still uses the buffering pipeline contract described above. Prefer honest progress logs and explicit process ownership to a recipe that silently loses output or exit information.
For a long build with a disk budget, start an owned process group, poll the filesystem, and retain its log from the beginning. On Unix, detached: #t creates that group and process-signal! can terminate it and its descendants:
(requires (tools df))
(define child (spawn compiler detached: #t out: "build.log" err: 'merge))
(let loop ()
(when (process-alive? child)
(define available
(string->number (trim (cadr (lines df -B1 --output=avail /)))))
(if (< available 25769803776)
(process-signal! child 'kill)
(begin (sleep 10) (loop)))))
(unless (= (process-wait child) 0) (error "build failed; inspect build.log"))Choose a stop threshold above the required free-space floor to allow for writes between polls. Reap the child after stopping it, and keep its evidence. When isolating HOME, invoke an installed version's real executable by its absolute path: the sigil launcher needs the usual home to find the selected version. Child CPU affinity and priority can be set by starting the driver with taskset and nice; descendants inherit both.
Test a rebuilt CLI
For a CLI regression, run the Sigil harness with a known prior interpreter and pass the rebuilt executable as its first argument. Resolve that argument before changing directories, invoke it as a child, and retain its structured outcome:
(define compiler (realpath (arg 1)))
(define result ($? ,compiler task --config dev own-build
cwd: ,fixture timeout: 60))
(write-text (path evidence "task.log")
(str (format-outcome result) "\n" (stdout-of result) (stderr-of result)))This keeps the harness independent of the build driver being tested. Give the fixture explicit local dependencies so a missing registry prerequisite cannot masquerade as the intended negative control. The standalone task context gate at test/integration/test-standalone-task-context.sgl uses this pattern.
Independent arithmetic oracles
Keep a compiler regression's orchestration in Sigil while asking an independent interpreter to evaluate the reference arithmetic. For example, Guile can compute an exact rational result that Sigil cannot represent:
(requires (tools guile))
(define expression "(write (* 7 (- (/ 100000000000000000000 7) (/ 99999999999999999999 7))))")
(define expected (string->number (out guile --no-auto-compile -c ,expression)))
(unless (= expected 1) (error "unexpected exact rational reference" expected))Generate numeric input with format and ~s, then read the oracle's numeric output as data. The independent reference expression uses the test-harness exception; case generation, process handling, and verdicts remain in Sigil. The subtraction gate at test/integration/test-exact-subtraction.sgl applies this pattern to fixed and random operands on bytecode and native backends.
Enumerate directories
On Sigil 0.24.4, glob returns matching files, without directories. Use directory-list when enumerating directories, and join each returned name to its parent before testing it:
(define parent "/path/to/inputs")
(define directories
(filter directory?
(map (lambda (name) (path parent name)) (directory-list parent))))A disposable probe with a file and directory returned only the file from (glob (path parent "*")), and both names from (directory-list parent). For a sysfs attribute, glob the files directly, for example (glob "/sys/class/ieee80211/phy0/rfkill*/soft"), rather than the directories.