Shell Scripting
Selected topics from Chapters 24 and 25.
  1. Shell scripts.
    1. Executable text files containing a series of commands.
    2. Execute by simply running the commands.
    3. Exactly the same commands are available command-line and script. Some are just more useful in one place or the other.
  2. Making a script.
    1. Make text file.
    2. First line is #!/bin/bash
    3. Additional lines are commands.
    4. Lines starting with # are comments.
    5. Chmod the file executable (and readable).
    6. Run the file by typing its name.
      1. Must be on the PATH to use the simple name.
      2. Can run with absolute path.
      3. Use ./filename from the same directory.
    7. No particular extension needed.
      1. Usually just none.
      2. If one is used, .sh is conventional.
    #!/bin/bash # This is a shell script echo "Hello, World!"
  3. Where to put shell scripts?
    1. On the PATH, in the usual places for executables, /bin, /usr/bin, /sbin or /usr/sbin.
    2. Local executables (script or not) often put in /local/bin, /usr/local/bin, /local/sbin or /usr/local/sbin.
    3. Personal executables in ~/bin.
      1. Create the directory.
      2. If needed, add to PATH in .bash_profile
  4. Variables.
    1. Set and use as we know
      frank=10 echo "Frank is $frank"
    2. Variables often set using substitution
      frank=$((frank+1)) lsloc=$(which ls | tail -1)
    3. Configuration variables like $USER and $HOME are available and often useful.
    4. Some pre-defined variables:
      $1, $2, $3, …Each command-line argument
      $*All the command-line arguments
      $@All the command-line arguments, quoted
      $#Number of command-line arguments
      $0Name of the script
  5. Here Documents
    1. A form of I/O redirection from the text of the script itself.
      cat <<END This text will be read by cat, and sent to standard output END cat << DONE >somefile.txt This text will be read by cat and written to the file called "somefile.txt". Note that any ending string can be used. DONE
    2. Using <<- instead discards leading tabs on each line.