Official website for Linux User & Developer

Shell scripting for system administrators: beyond the basics

by Swayam Prakasha

In an earlier article, we studied the fundamental aspects of shell scripting and covered topics such as redirection, variables, arithmetic expansions and control constructs. In this part, we will focus on more advanced concepts that are useful for system administrators and software developers…

In a script, we need to know that operations execute in order of precedence – that is, the higher-precedence operations execute before the lower-precedence ones. If we have equal precedence operators, then the order of evaluation will be from left to right. An internal function $RANDOM is available for generating a random number. It returns a pseudorandom integer in the range of 0 to 32767. We have echoed the value of $RANDOM twice and following is the output that we received.
[sourcecode language=”bash”][root@localhost scripts]# echo $RANDOM
[root@localhost scripts]# echo $RANDOM
[root@localhost scripts]#
A large number of string manipulation operations are available and they can be used to achieve various functionalities. Let us have a look at some of them…

a. String length – There are different methods by which one can obtain the length of a specific string. All the following will return the string length (this functionality is similar to strlen() in C language):
[sourcecode language=”bash”]1. ${#string}
2. expr length $string
3. expr “$string” : ‘.*’
b. Length of matching substring at beginning of string – This can be achieved by using
the following:
[sourcecode language=”bash”]expr match “$string” `$substring`
c. Index – If we want to get the numerical position in $string of the first character in $substring that matches, we can use following code:
[sourcecode language=”bash”]expr index $string $substring
For example, if our string is pqrstuvwC12, then the following execution will returns a value of 9 (since C is the first character in the substring that matches):
[sourcecode language=”bash”]echo `expr index “$string” C1`
d. Extracting a substring.
${string:position} – This will extract the substring from the original string at $position.
${string:position:length} – We can also specify the number of characters to be extracted.

Consider the following part of a script:
[sourcecode language=”bash”]String=abcdefghi122345
Echo ${String:7:3}
As expected, the output will be hi1.

e. expr substr $string $position $length – This will extract $length characters from $string starting at $position.

Continue to page 2…

You can find the first part of our Shell Scripting for System Administrators article here.

Click here to return to the Linux User & Developer homepage

twitter follow us
Pages: 1 2 3
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.