bash parameter expansion
Permalink: https://wizardzines.com/comics/parameter-expansion/
bash parameter expansion
Permalink: https://wizardzines.com/comics/parameter-expansion/
@arensb @b0rk_reruns This reminds me of the plan9 shell rc’s default prompt:
;
which nicely nops when copy pasting multiple lines. And I think recently I stole a variant from @cross:
: user@hostname/cwd;
Instead of the common:
user@hostname:cwd$
${var:-...}
and ${var:?...}
, the colon is not required. Its presence indicates that empty variables (i.e. variables containing an empty string) are to be treated like unset variables. If you write ${var-...}
or ${var?...}
, the default value or error message only kicks in if the variable is genuinely unset, not just empty.For the prefix/suffix removal, you can choose between removing the shortest or longest matching pattern by using %/# vs. %%/##:
$ var="Hello World"
$ echo ${var%l*}
Hello Wor
$ echo ${var%%l*}
He
$ echo ${var#*l}
lo World
$ echo ${var##*l}
d
@b0rk_reruns @b0rk Does anyone have any good way of remembering what each of these syntaxes do? Each time I use them, I have to look it up in the docs to make sure I'm using the right thing.
How do you remember which of ${var#pattern} or ${var%pattern} removes a prefix or a suffix?
I have such a hard time remembering I look it up each time. Anyone have some tricks for remembering?
@unlambda @b0rk_reruns @b0rk If it helps I work with a lot of these regularly and have to look it up every time.
Only when I’ve used it that day but not with too many in between can I get away with going from memory.
@unlambda @b0rk_reruns @b0rk my trick is to switch to another language when i start needing this kind of things 😆. You can do a lot in bash, but the syntax is just too cryptic to do anything complex. the default value is an exception, it often comes handy in simple scripts.
about docs:
«[I do not] carry such information in my mind since it is readily available in books. ...The value of a college education is not the learning of many facts but the training of the mind to think.» Albert Einstein.
@unlambda @b0rk_reruns @b0rk # is before $ on a keyboard, so it’s for prefix. % is after — so suffix
At least that’s how I remember
this says “null” to mean “empty”?
by contrast, Python’s os.environ.get(“name”) distinguishes “” for empty and None for unset
ditto TypeScript, except “null” is their spelling of None
p.s. thanks especially for so strongly surfacing the x// vs x/ distinction for replacing all or just one, i had forgotten that syntax till you came to remind us here
I LOVE THIS
just used to glob my latest generated files and create a directory from it
```
TRAINING_DATA=$(ls -lt training_data* | rev | head -n1 | cut -d' ' -f 1 | rev) \
OUTPUT_DIR="${TRAINING_DATA%.*}" \
mkdir models_$OUTPUT_DIR
```