Bilun Ba
Bilun Ba

Reputation: 37

What does "output_dir="${1%/}" mean in .sh file?

I have not seen the usage like this.Anyone can provide relevant information? The source code im2txt

Upvotes: 2

Views: 489

Answers (2)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16039

See the bash manual:

${parameter%word} ${parameter%%word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. [...]

I emphasized the relevant alternative. The parameter in question is $1, i.e. the first command line argument the script was called with. The pattern is a simple / which will be removed if present. In other words, the expansion removes an optional trailing slash.

Demonstration (the y case shows that it's just a trailing pattern, z demonstrates no match):

$ x=aaa/; y=aaa/bbb; z=aaa; echo "$x    ->      ${x%/}"; echo "$y       ->      ${y%/}"; echo "$z       ->      ${z%/}"
aaa/    ->      aaa
aaa/bbb ->      aaa/bbb
aaa     ->      aaa

Upvotes: 4

Bogsan
Bogsan

Reputation: 691

It basically removes the last "/" character from the ending of the first string received as a parameter of the script in cause. If you had "/home/users/" as a string, then output_dir would become "/home/users" You can find more details on string manipulation in bash here.

Upvotes: 1

Related Questions