Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know that shell scripts just run commands as if they were executed in at the command prompt. I'd like to be able to run shell scripts as if they were functions... That is, taking an input value or string into the script. How do I approach doing this?

share|improve this question
up vote 20 down vote accepted

The shell command and any arguments to that command appear as numbered shell variables: $0 has the string value of the command itself, something like script, ./script, /home/user/bin/script or whatever. Any arguments appear as "$1", "$2", "$3" and so on. The count of arguments is in the shell variable "$#".

Common ways of dealing with this involve shell commands getopts and shift. getopts is a lot like the C getopt() library function. shift moves the value of $2 to $1, $3 to $2, and so on; $# gets decremented. Code ends up looking at the value of "$1", doing things using a caseesac to decide on an action, and then doing a shift to move $1 to the next argument. It only ever has to examine $1, and maybe $#.

share|improve this answer
the C getopt() is an extremely established standard, but the getopt executable is not the same across distro/platform. I'm a now fully converted getopts user, as it is a POSIX standard. It works great with dash also, which is my preferred script shell – TechZilla Feb 10 '12 at 23:40
$/shellscriptname.sh argument1 argument2 argument3 

You can also pass output of one shell script as an argument to another shell script.

$/shellscriptname.sh "$(secondshellscriptname.sh)"

Within shell script you can access arguments with numbers like $1 for first argument and $2 for second argument and so on so forth.

More on shell arguments

share|improve this answer

You can access passed arguments with $n where n is the argument number - 1, 2, 3, .... You pass the arguments just like you would with any other command.

$ cat myscript
echo "First arg: $1"
echo "Second arg: $2"
$ ./myscript hello world
First arg: hello
Second arg: world
share|improve this answer
./myscript myargument

myargument becomes $1 inside myscript.

share|improve this answer

The form

$ ./script.sh "$@" 

is the most convenient for argv. The arg delimiter is whitespace, but can be changed. Don't remember how off-hand. Then use

 $1, $2, shift, if [ $# -ne 3 ] 

to control flow. I don't usually embrace getopts if a case ... esac will suffice.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.