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?
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
/home/user/bin/script or whatever. Any arguments appear as
"$3" and so on. The count of arguments is in the shell variable
Common ways of dealing with this involve shell commands
getopts is a lot like the C
getopt() library function.
shift moves the value of
$2, and so on;
$# gets decremented. Code ends up looking at the value of
"$1", doing things using a
esac 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
You can access passed arguments with
n is the argument number -
1, 2, 3, .... You pass the arguments just like you would with any other command.
$ cat myscript #!/bin/bash echo "First arg: $1" echo "Second arg: $2" $ ./myscript hello world First arg: hello Second arg: world
$/shellscriptname.sh argument1 argument2 argument3
You can also pass output of one shell script as an argument to another shell script.
Within shell script you can access arguments with numbers like
$1 for first argument and
$2 for second argument and so on so forth.
In the shell script ; it becomes the variable name $1 . The second word becomes the variable name $2 and so on .
cat << 'EOF' > test echo "First arg: $1" echo "Second arg: $2" echo "List of all arg: $@" EOF sh test hello world
More maybe found in the shell (sh) manual at http://heirloom.sourceforge.net/sh/sh.1.html
If you're familiar with Python argparse, and don't mind calling python to parse bash arguments, use bash argparse (https://github.com/mattbryson/bash-arg-parse),