I encountered the following issue with parameter expansion while trying to write a script for setting the metric of my VPN's default route.
For testing purposes, I've simplified the code to the following:
vpn_route='default via 10.106.160.1 proto static metric 50'
echo ip route del "$vpn_route"
echo ip route add "${vpn_route/metric +([0-9])/metric 101}"
echo ip route add "${vpn_route/%metric */metric 101}"
Once I remove the echo commands, this should
- delete the existing default route
- Create a new route with the
metric <number>
part replaced bymetric 101
For testing, I added a second variant with a less specific pattern.
If I execute this code in an interactive bash shell, it works as expected:
$ vpn_route='default via 10.106.160.1 proto static metric 50'
$ echo ip route del "$vpn_route"
ip route del default via 10.106.160.1 proto static metric 50
$ echo ip route add "${vpn_route/metric +([0-9])/metric 101}"
ip route add default via 10.106.160.1 proto static metric 101
$ echo ip route add "${vpn_route/%metric */metric 101}"
ip route add default via 10.106.160.1 proto static metric 101
However, if I execute the script, I get the following:
$ cat lower-vpn-priority.sh
#!/usr/bin/env bash
vpn_route='default via 10.106.160.1 proto static metric 50'
echo ip route del "$vpn_route"
echo ip route add "${vpn_route/metric +([0-9])/metric 101}"
echo ip route add "${vpn_route/%metric */metric 101}"
$ bash lower-vpn-priority.sh
ip route del default via 10.106.160.1 proto static metric 50
ip route add default via 10.106.160.1 proto static metric 50
ip route add default via 10.106.160.1 proto static metric 101
Can anyone explain to me what's going on here? :)