tags:

views:

73

answers:

2

I just learned that I could use chmod make myscript.sh executable and the run it as $ ./myscript.sh But how can I attach a custom command to it, like $ connectme [options] ?

+3  A: 

You need to do two things:

  1. Give the name you want to use. Either just rename it, or establish a link (hard or symbolic). Make sure the correctly named object has the right permissions.
  2. Make sure it is in you path. But putting "." in you PATH is a bad idea (tm), so copy it to $HOME/bin, and put that in you path.

A completely different approach. Most shells support aliases. You could define one to run your script.


Note: The environment variable PATH tells the shell where to look for programs to run (unless you specify a fully qualified path like /home/jdoe/scripts/myscript.sh or ./myscript.sh), it consists of a ":" seperated list of directories to examine. You can check yours with:

$ printenv PATH

resulting for me in

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin:/usr/X11R6/bin

which are the usual directories for binaries. You can add a new path element with (in /bin/sh and derivatives):

$ export PATH=$PATH:$HOME/bin

in csh and derivatives use

$ setenv PATH $PATH:$HOME/bin

either of which which will result in the shell also searching ~/bin for things to run. Then move your script into that directory (giving ta new name if you want). Check that you execute permissions for the script, and just type its name like any other command.

Fianlly, the use of a ".sh" extension to denote a shell script is for human consumption only. Unix does not care about how you name your script: it is the so-called "shebang" ("#!") on the first line of the script that the OS uses to find the interpreter.

dmckee
I dont want alias, and could you give me some examples of how renaming work? I thought no matter what you name it, you always run as /usr/dir/myscript.sh
derrdji
I think I interpreted the question the wrong way.
Pablo Santa Cruz
+1  A: 

You need to learn about arguments in BASH PROGRAMMING. Here is a good tutorial on them. Check section #4 out.

Basically, you need to use special variables $1, $2, $3 to refer to first, second and third command line arguments respectively.

Example:

$ ./mycript.sh A-Rod

With myscript.sh being:

#!/bin/bash

echo "Hello $1"

Will print:

Hello A-Rod
Pablo Santa Cruz
As a Red Sox fan, I feel obligated to -1 this answer....
phsr
hehehehehehe... No! C'mon! I meant tennis' A-Rod (Andy Roddick) ;-)
Pablo Santa Cruz
Thanks a lot for the tut. I know about arguments, but what I need is say the program has an interface like "$ connectme [options]" instead of running it as "./myscript.sh"
derrdji