Monday, October 25, 2010

String manipulation using UNIX commands

Extract substring based on index.

e.g.
first_name=Jayanthi
short_name=${first_name:0:3}
echo $short_name

Output: Jay


Replace all occurrences of a text
:%s/search_string/replacement_string/g

cut example

We usually assign some value to a variable and reuse the variable. There could also be situations where we need the variable name when value is passed.

Create a file named server with the following content.
server_qa_apache=1.1.1.1
server_production_jboss=2.2.2.2

I would like to pass IP as input and obtain the variable name.
 grep 1.1.1.1 servers| cut -d'_' -f2
Output: qa

 grep 2.2.2.2 servers| cut -d'_' -f2
Output: production

In case, you have more than one place in a file where 1.1.1.1 is used, you can limit the grep results matching the first one.
grep 1.1.1.1 servers -m 1| cut -d'_' -f2

Limit results with grep

Create a file named servers with the following
server_apache1=1.1.1.1
server_apache2=1.1.1.2
server_apache3=1.1.1.3

grep apache servers
will return output
server_apache1=1.1.1.1
server_apache2=1.1.1.2
server_apache2=1.1.1.3

To limit the grep results, try
grep apache servers-m 1
Output: server_apache1=1.1.1.1

grep apache servers-m 2
Output:
server_apache1=1.1.1.1
server_apache2=1.1.1.2

Nested UNIX variables with eval

eval is a nice function and particularly useful to resolve the value of nested unix variables properly. Here is a scenario.

You have 3 apache servers that belong to different environments.
server_qa_apache=1.1.1.1
server_test_apache=2.2.2.2
server_production_apache=3.3.3.3

Assume you pass the environment as an input variable and want to obtain the server IP.
Environment can be qa, test or production.

ENV=$1
SERVER_IP=${server_$ENV_apache}

-bash: ${server_$ENV_apache}SERVER_IP=${server_$ENV_apache}: bad substitution
The above line will report the error because of nested unix variable.

Use a backslash for nested unix variables.
echo \${server_${ENV}_apache}

The above line will output the variable name similar to
${server_production_apache}

To resolve the value of the variable correctly, you can use eval
eval SERVER_IP=\${server_${ENV}_apache}
echo $SERVER_IP

Thursday, October 7, 2010

NTP Synchronization

NTP Setup in RHEL

1) cat /etc/ntp.conf
Add servername

2) Check config
su -
chkconfig --list ntpd

3) NTP operations commands
service ntpd start
service ntpd stop
service ntpd restart

4) Synchronize instantly
ntpdate -u {ntp_server_name}

Newer›  ‹Older