View on GitHub

Computational Techniques for Life Sciences

ARGUMENTS

We’ve seen earlier that space-separated text after a script can be accessed with special variables called arguments.

Variable Meaning
$0 Name of script
$1 Positional parameter #1
$2 - $9 Positional parameters #2 - #9
${10} Positional parameter #10
$# Number of positional parameters
”$*” All the positional parameters (as a single word)
(note : Must be quoted, otherwise it defaults to “$@”.)
”$@” All the positional parameters (as separate strings)
${#*} Number of command line parameters passed to script
${#@} Number of command line parameters passed to script
$? Return value
$$ Process ID (PID) of script
$_ Last argument of previous command
$! Process ID (PID) of last job run in background

We’ve used positional parameters before:

prompt> cat int_math.sh
#!/bin/bash

# $1 and $2 are command line arguments that grab the nth command line values

ADD12=$(( $1 + $2 )) ; echo "${1} + ${2} =" ${ADD12}
SUB12=$(( $1 - $2 )) ; echo "${1} - ${2} =" ${SUB12}
MUL12=$(( $1 * $2 )) ; echo "${1} * ${2} =" ${MUL12}
DIV12=$(( $1 / $2 )) ; echo "${1} / ${2} =" ${DIV12}
MOD12=$(( $1 % $2 )) ; echo "${1} % ${2} =" ${MOD12}
EXP12=$(( $1 ** $2 )) ; echo "${1} ^ ${2} =" ${EXP12}

DISCUSS: What would happen if I supplied more than 2 values for our Integer batch calculator?



Additional ways to get external values into bash scripts

read command

The read command pauses and waits for the user to provide input followed by a <return>:

prompt> read bubble
pop<return>
prompt> echo $bubble
pop

EXERCISE: Write a script that tells you it’s own name, how many arguments there were, and what they are.

prompt> vi report_args.sh


#!/bin/bash

script=$0

num_args=$#

cmdline_args="${@}"

echo Script $script had $num_args args : $cmdline_args

echo -n "type anything then hit return:"
read more_var

echo "Additional variables read: $more_var"


prompt> chmod +x report_args.sh
prompt> ./report_args.sh apples pears 55 ruby diamond
Script ./report_args.sh had 5 args : apples pears 55 ruby diamond
type anything then hit return:stellar<return>
Additional variables read: stellar


Prev strings | Next ARRAYS | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center