9
How does this code work? (sh.itjust.works)
submitted 1 month ago by zarkanian@sh.itjust.works to c/bash@lemmy.ml

I'm studying bash, and I came across this Stackoverflow thread which contains this bit of code:

var="abcde"
echo ${var%d*}

The output is abc, but I can't figure out why. I understand that %d is used to indicate an integer number and * represents anything, but I can't figure out why those together would truncate var to only 3 characters.

top 3 comments
sorted by: hot top controversial new old
[-] beatnik86@lemmy.world 19 points 1 month ago

That's manipulation of the string held in var. Dollar sign and curly braces wrap the variable, the single percent sign say remove the shortest matching substring from the end of the variable contents, and the 'd*' is the substring to match, a lowercase d followed by any characters in this instance. var will still hold the entire original string, only the echo output is modified here. You can find more documentation here, https://tldp.org/LDP/abs/html/string-manipulation.html.

[-] SpaceNoodle@lemmy.world 4 points 1 month ago

That's the exact Bible I would have linked to.

[-] bbpngn@lemmy.eco.br 1 points 1 week ago

You may be confusing that %d with printf syntax. I'm not entirely sure, but I think what the percent sign means is delete everything from the end of string until the first occurence of letter "d"

this post was submitted on 07 Oct 2024
9 points (100.0% liked)

Bash

720 readers
1 users here now

Talk about the Bash Shell and Bash scripting

founded 4 years ago
MODERATORS