Ezra
Ezra

Reputation: 1481

bash variable declaration with % operator

I'm going through a bash script and I can't understand this statement not able to search for it:

IPV=${IPTABLES%tables}

what does this statement means?

Upvotes: 0

Views: 77

Answers (2)

shellter
shellter

Reputation: 37298

A variable like you show ${IPTABLES%table} is called a parameter, and the % is a parameter modifier.

There are 4 basic parameter modifers in this "set"

  ${var#str*x}   #   removes str and the shortest match to x from left side of variable's value 
  ${var##str*x}  # removes longest match of str and everything to the farthest x


  ${var%str}   # removes str from the right side of the variable's value
  ${var%x*str} # removes shortest match of x*str from the right side 
  ${var%%x*str}  # removes longest match of x*str from right side

So ${var#X} and ${var##X} count for 2, and ${var%X}, ${var%%X} make another two.

There are others, depending on versions and bash, vs ksh, vs zsh

So play with

 var=abcxstrxyz
 echo ${var%#str}
 echo ${var%str*}
 echo ${var%%str}
 echo ${var%%str*}

Etc to get a sense of what this can do.

IHTH

Upvotes: 1

jas
jas

Reputation: 10865

This is an example of parameter substitution (and not related to the math operator). There are many more examples here: http://tldp.org/LDP/abs/html/parameter-substitution.html

${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var.

${var%%Pattern} Remove from $var the longest part of $Pattern that matches the back end of $var.

For example:

$ export IPTABLES=footables
$ echo ${IPTABLES%tables}
foo

Upvotes: 2

Related Questions