Reputation: 11
I am confused about the below regular expression I found in a shell script
#!/bin/sh
prog=${0%%.sh}-via.sh
Anyone give me a valuable information
Upvotes: 0
Views: 65
Reputation: 2544
When you run a script, the variable $0
is automatically set with the name of the script (which may or may not contain the folder, but I think this is not relevant to your question).
In bash the ${0}
syntax can be used to fetch the same variable, but in the braces you can add extra processing to the variable. In your example:
${0%%.sh}
will remove the ".sh" part at the end of the string, using parameter substitution.
prog=${0%%.sh}-via.sh
will add -via.sh
at the end, and assign it to prog
.
All in all, what it does is replacing the .sh
by -via.sh
. Let's say your script is called "myscript.sh", then prog
will be assigned the value "myscript-via.sh".
As a side note, I would recommend starting your script with #!/bin/bash
instead of #!/bin/sh
because parameter substitution is a bash feature. More info about why it matters here.
Upvotes: 2
Reputation: 8581
${0%%.sh}
removes the suffix .sh
from the variable 0
(it contains the name of the script) and appends -via.sh
. The result is stored in prog
which is <script_name_without_extension>-via.sh
For further reference see this related question: Remove a fixed prefix/suffix from a string in Bash
Upvotes: 1
Reputation: 5762
There are no regular expressions involved in that script.
${0}
is the name of the called script.
The %%
operator removes a matching suffix pattern., so ${0%%.sh}
is the name of the called script without the final ".sh".
Finally, ${0%%.sh}-via.sh
is the name of the called script without the final ".sh" and appending "-via.sh".
That value is assigned to variable prog
.
Upvotes: 4