Easy but useful bash functions (grip and sshcp)

If you’re like me and easily forget exact syntax of commands and don’t really feel like dedicating the necessary block of brain space reserved for the root user to memorization of exact syntax, I offer you these simple bash functions.  Toss them into your ~/.bashrc file for instant fun (protip: type bash to reload bash after you have added these to load them up without re-logging) or put them into /etc/bash.bashrc to apply them to all users using bash on your system.

The first function searches through the text of all the files in your current directory.  Very useful for, say, debugging a PHP script you didn’t write and can’t track down where that damn MySQL connect string actually is.

Usage: grip [text]

function grip {
grep -ir “$1″ “$PWD”
}

Yes, it is VERY simple, however I believe you will find it is an indispensable tool for hunting stuff down and cutting the time searching by at least 9000 times.

The next script looks a bit more complex, partially because I commented it so you could see what is going on, partially because it’s so customizable.  It’s for running scp with preset variables, you could maybe make a few of these for different servers you use scp to send files to, again a big time-saver.  Note that this assumes that scp is in your $PATH.  If it isn’t, edit the final command that actually runs scp to whatever is relevant to your configuration.

Usage: scp file [remotefile]

function sshcp {
#ssh cp function by seanp2k
FNAME=$1
#the name of the file or files you want to copy
PORTNUM=”22″
#the port number for ssh, usually 22
HOSTNAM=”192.168.1.1″
#the host name or IP you are trying to ssh into
if [ $2 ]
then
RFNAME=”:$2″
else
RFNAME=”:”
fi
#if you specify a second argument, i.e. sshcp foo.tar blah.tar,
#it will take foo.tar locally and copy it to remote file bar.tar
#otherwise, just use the input filename
USRNAME=”root”
#you should never allow root login via ssh, so change this username

scp -P “$PORTNUM” “$FNAME” “$USRNAME@$HOSTNAM$RFNAME”

}

Whew.  You will have to configure this for it to work correctly, unless you want to log into 192.168.1.1 on port 22 with username “root” and copy files to root’s home directory.  I believe you can specify a different path in the second argument to sshcp assuming that the user you are logging in as has permission to write to that directory.  Example: sshcp somefile.conf /etc/apache2/httpd.conf .  Note that I have not tried this and I would not be surprised if it didn’t work.  Also note that it will overwrite the destination file without conformation.  You have been warned.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.