Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

While bash scripts can be written to perform a single function, another style is to have a script perform multiple functions, where the functionality to be performed is specified by the first command argument to the script. This is the script style we 'll will explore here.

Code Block
languagebash
my_script.sh helloWorld      # invoke the "helloWorld" functionality of my_script.sh
my_script.sh goodbyeWorld    # invoke the "goodbyeWorld" functionality of my_script.sh

...

The first line (#!/bin/bash) is called the shebang which consists of #! characters followed by the full path to the program which should execute the script, if it is invoked without an execution context (and if it has execute file permissions of course (smile)).

Code Block
languagebash
# Call a script directly. 
# As long as it marked as executable (chmod +x), the shell 
# peeks at the shebang line and passes the script to that program.
# Here the shell (bash) passes the script to itself (/bin/bash)
~/workshop/step_01.sh

# Call a script specifying the executing program. The shebang line will be ignored.
# In this case, the script does not even have to be marked as executable!
bash ~/workshop/step_01.sh

...

The variable's value is referenced by prefixing the variable name with the dollar sign $, or by enclosing it in braces prefixed by the dollar sign ${}. Usually these two forms are equivalent, except:

  • when referencing a positional argument variable with more than one digit (e.g. ${10})
  • to separate the variable evaluation from text immediately following (e.g. ${prefix}_file.txt)
    • since underscore characters ( _ ) are allowed in variable names, the braces are needed so that the shell does not think the variable name is prefix_file.

...

  • individual positional variables $1 $2 ... $9  ${10}  ${11}...
  • or $@ to refer to all of the arguments
  • and $0 to refer to the script file name itself

Note that while a function can have many arguments, the function definition never contains anything in its ( ) "formal argument list". Weird, eh?

...

In our script, the shift keyword "pops" the first element off the argument list.

...

Expand
titleSolution


Code Block
languagebash
# Empty quotes createrepresent an empty argument
~/workshop/step_01.sh helloWorld '' "My name is" Anna B


...

Code Block
languagebash
# Wihout quotes, all argument grouping by the script caller is lost!
helloWorld $@

# With quotes, argument quoting by the script caller is preserved
helloWorld "$@"

...