Linux Blog

Reworking Shell Scripts

Filed under: Shell Script Sundays — TheLinuxBlog.com at 7:02 am on Sunday, August 24, 2008

To me shell Scripts are all about automation, their primary purpose is to get stuff done. If you have a one liner, snippet or other script you use on a regular basis, have you thought about how you could rework it for it to become more in handy?

Lets take last weeks snippet from this column. It was a simple one liner to reconnect to a host. Now, I knew when I posted this article that it was a helpful snippet of code. Now, how can this script be adapted to be a neat utility that we use on a regular basis? Over the next few week’s we’ll find out.

The first thing that I will note on is that this script or shell snippet is a pain to remember. Does a script save you time if you can’t remember how it works? Is it worth the hassle? Not exactly. So, in order to make this snippet a little better the first thing we are going to do is add something that it needs: parameters. Adding parameters to shell scripts is actually easy, much easier than adding parameters to some other languages that we wont mention. although this script does not use it getopts can be used. I’ve covered how to do this with getopts in other posts. Just do a site search (located at the bottom of the right bar for getopts.)

So, here is the modified script that automatically reconnects to a host by using ping and SSH:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash
 
# Sleep Time Default: 15 seconds
STIME=15
 
# Set a default user up
USERNAME=LinuxBlog
 
#usage function
usage () {
echo -e "Usage: $0 host [user] [Sleep Time]"
}
 
# display usage if no host is specified
[ -z $1 ] && { usage && exit 1; }
 
# set the variables
[ $1 ] && { HOST=$1; }
[ $2 ] && { USERNAME=$2; }
[ $3 ] && { STIME=$3; }
 
# trying:
echo -e "host: $HOST \nuser: $USERNAME \ndelay: $STIME"
 
while ! ping -W 1 -c 1 $HOST 2>&1 >/dev/null; do true; done && echo "Successful waiting: $STIME secs"; sleep $STIME; ssh $USERNAME@$HOST

Now that you have that done, all you need to do is give the file a name (I called mine ssh_auto) and put it in a folder in your path. Use the filename and parameters defined in the script to connect to the host.

The next shell scripting article I demonstrate how you can further rework shell scripts to better suit your needs.





Random Man Pages:
gpasswd
kbd
fsetxattr
ati

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>