DEPARTMENT OF COMPUTING

Scripting


How to


How to


Script example 1

#!/bin/bash
# here is a comment
echo 'Hello world'

How to Run our script

Remember that the first value of every command is the command itself. But our script is a file, but not a command right?

Actually, all of our commands are stored as files. It is our PATH variable that determines the directories that the computer looks in for commands that we type. To run a command (a script file) that isn’t in one of the PATH directories - we can add our desired directory to the PATH variable, add our script to an existing command PATH, type the full absolute path to our script, or simply begin our command with a ./ (dot slash) to say “Look for the command in the current directory”.

For our purposes the easiest way to test our script is to type

./myscript.sh


Variables

A variable is a placeholder in a script for a value that will be determined when the script runs. Variables’ values can be passed as parameters to a script, generated internally to a script, or extracted from a script’s environment.


Variable example

    #!/bin/bash
    #foo.sh
    # execute with ./foo.sh arg1 arg2
    echo "You just input " $1 $2

Variables within the script


Side note

Variable names can be surrounded by optional curly braces when expanding. Can be useful when a vriable name becomes ambiguous:

filename="myfile"
touch $filename
mv $filename $filename1 #this fails (bash thinks 1 is part of var name)
mv $filename ${filename}1 #this works

Conditional expressions


More conditionals

    if [ condition ]
      then
       commands
      else
       other-commands
    fi

The test does need to have spaces around the brackets.


Comparison operators


Loops

Do something more than once:

    for i in $(seq 1 10); do
        touch file$i.txt
    done

Textbook Time

The textbook reading is optional.

When you’ve learned the basics of scripting you can write a script in many languages. Just like with any type of programming the only difference is the syntax.


Last Updated 12/15/2017