Exercise

Our First Bash Script Exercise

Task

Write a script, make it runnable, and get it to the point where you can run it by name from anywhere.

Host
servera
Script
/home/student/scripts/take_inventory.sh
  1. Write the script in your home directory

    Line 1 is the hashbang. It names the interpreter that will run the rest of the file.

    cd ~
    vim take_inventory.sh
    #!/bin/bash
    echo "Taking inventory"
    ls > inventory
    cat take_inventory.sh
  2. Try to run it and fix the permission

    A new file is not executable, so the kernel will not run it.

    ls -l take_inventory.sh
    ./take_inventory.sh

    Add the execute bit and look at the change.

    chmod a+x take_inventory.sh
    ls -l take_inventory.sh
  3. Run it with ./

    ./ means run the file at this path.

    ./take_inventory.sh
    cat inventory
  4. Find out why the bare name does not work

    take_inventory.sh

    Bash searches PATH, and your home directory is not on it. Look at what is.

    echo $PATH
  5. Move it onto your PATH and run it by name

    mv take_inventory.sh ~/scripts/
    take_inventory.sh

    No ./ this time. Bash found it on PATH, exactly the way it finds ls.

    Clean up

    rm -f ~/inventory