How To Use Bash Parameter Substitution Like A Pro
Syntax
You can use variables to store data and configuration options. For example:
Use echo or printf command to display variable value:
OR
The parameter name or symbol such as $dest to be expanded may be enclosed in braces
It is optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.
dest="/backups"
Use echo or printf command to display variable value:
echo "$dest"
OR
printf "$dest\n"
The parameter name or symbol such as $dest to be expanded may be enclosed in braces
echo "Value ${dest}"
It is optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.
#1: Setting Up Default Shell Variables Value
The syntax is as follows:
If parameter not set, use defaultValue. In this example, your shell script takes arguments supplied on the command line. You’d like to provide default value so that the most common value can be used without needing to type them every time. If variable $1 is not set or passed, use root as default value for u:
Consider the following example:
You can now run this script as follows:
Here is another handy example:
Use this substitution for creating failsafe functions and providing missing command line arguments in scripts.
#1.1: Setting Default Values
The syntax is as follows:
The assignment (:=) operator is used to assign a value to the variable if it doesn̢۪t already have one. Try the following examples:
Sample outputs:
vivek
Now, assign a value foo to the $USER variable if doesn’t already have one:
Sample outputs:
vivek
Unset value for $USER:
Sample outputs:
foo
This make sure you always have a default reasonable value for your script.
Tip: ${var:-defaultValue} vs ${var:=defaultValue}
Please note that it will not work with positional parameter arguments:
#2: Display an Error Message If $VAR Not Passed
If the variable is not defined or not passed, you can stop executing the Bash script with the following syntax:
This is used for giving an error message for unset parameters. In this example, if the $1 command line arg is not passed, stop executing the script with an error message:
Here is a sample script:
#2.1: Display an Error Message and Run Command
If $2 is not set display an error message for $2 parameter and run cp command on fly as follows:
#3: Find Variable Length
You can easily find string length using the following syntax:
Here is a sample shell script to add a ftp user:
Each Linux or UNIX command returns a status when it terminates normally or abnormally. You can use command exit status in the shell script to display an error message or take some sort of action. In above example, if getent command is successful, it returns a code which tells the shell script to display an error message. 0 exit status means the command was successful without any errors. $? holds the return value set by the previously executed command.
#4: Remove Pattern (Front of $VAR)
The syntax is as follows:
You can strip $var as per given pattern from front of $var. In this example remove /etc/ part and get a filename only, enter:
The first syntax removes shortest part of pattern and the second syntax removes the longest part of the pattern. Consider the following example:
You just want to get filename i.e. dnstop-20090128.tar.gz, enter (try to remove shortest part of $_url) :
Sample outputs:
/dns.measurement-factory.com/tools/dnstop/src/dnstop-20090128.tar.gz
Now try using the longest part of the pattern syntax:
Sample outputs:
dnstop-20090128.tar.gz
This is also useful to get a script name without using /bin/basename:
Create a script called master.info as follows:
Finally, create softlink as follows:
You can now call script as follows:
# ln -s master.info uploaddir.info
# ln -s master.info tmpdir.info
# ln -s master.info mem.info
....
..
You can now call script as follows:
# ./mem.info example.org
# ./cpu.info example.com example.net
#4.1: Remove Pattern (Back of $VAR)
The syntax is as follows:
Exactly the same as above, except that it applies to the back of $var. In this example remove .tar.gz from $FILE, enter:
Sample outputs:
xcache-1.3.0
Rename all *.perl files to *.pl using bash for loop as Apache web server is configured to only use .pl file and not .perl file names:
You can combine all of them as follows to create a build scripts:
If you turn on nocasematch option, shell matches patterns in a case-insensitive fashion when performing matching while executing case or [[ conditional expression.
#5: Find And Replace
The syntax is as follows:
Find word unix and replace with linux, enter:
You can avoid using sed as follows:
To replace all matches of pattern, enter :
You can use this to rename or remove files on fly
Here is another example:
The following function installs required modules in chrooted php-cgi process
#6: Substring Starting Character
The syntax is as follows:
Expands to up to length characters of parameter starting at the character specified by offset.
Extract craft word only:
To extract phone number, enter:
Summary: String Manipulation and Expanding Variables
For your ready references here are all your handy bash parameter substitution operators. Try them all; enhance your scripting skills like a pro:
${parameter:-defaultValue} | Get default shell variables value |
${parameter:=defaultValue} | Set default shell variables value |
${parameter:?”Error Message”} | Display an error message if parameter is not set |
${#var} | Find the length of the string |
${var%pattern} | Remove from shortest rear (end) pattern |
${var%%pattern} | Remove from longest rear (end) pattern |
${var:num1:num2} | Substring |
${var#pattern} | Remove from shortest front pattern |
${var##pattern} | Remove from longest front pattern |
${var/pattern/string} | Find and replace (only replace first occurrence) |
${var//pattern/string} | Find and replace all occurrences |
Comments
Post a Comment