💾 Archived View for simon.flounder.online › portable.gmi captured on 2024-05-12 at 14:50:07. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2021-12-03)

-=-=-=-=-=-=-

You might not need local (or typeset)

Bash, zsh, and ksh all have extensions that let you have local variables inside your functions. But this isn't necessary: you can accomplish (most of) the same thing using any POSIX shell, by changing your function declaration syntax slightly.

myfunc () (
  # Notice how we use parentheses instead of curly braces.
)

This makes myfunc run in a subshell, which means that you can modify variables, change the current directory, set shell options, and so forth, without the “outer” shell being affected. (Of course, this is an all-or-nothing approach, so it won't work for all functions. But if your shell script is long enough and complicated enough, you might want to rewrite it in a more maintainable language anyways.)

You might not need sed -i

Many sed implementations allow you to edit a file in-place by using a nonstandard “-i” option. Roughly, “sed -i.bak prog files...” works on almost everything, but “sed -i prog file” (no backup extension) won't — it fails on macOS and FreeBSD.

You might be able to get around this with feature tests and a little hackery, but it's fundamentally the wrong option: it's not specified by POSIX (and probably will never be). Instead, you should use ed or ex, both editors that were designed for editing files, not streams.

# Don't use this:
sed -i 's/var/replacement/g' "$file"
# Use this:
ex -s "$file" <<'EOF'
%s/var/replacement/g
wq
EOF

This usage should be pretty familiar to a vi user: the commands are just “ex commands” (see where the name comes from?) without the colon. A similar usage also works with ed:

ed -s "$file" <<'EOF'
,s/var/replacement/g
w
q
EOF

Or if you want it work for both:

"$oureditor" -s "$file" <<'EOF'
1,$s/var/replacement/g
w
q
EOF