3.7. Scripts

This information is provided in case you want it. You will not need it for this course.

A script is a file that contains commands. When you run the script, the commands are performed. This page describes briefly how to write and run scripts in Linux.

The first line of a script should give the command interpreter to use. If you want your script to be read by the bash command interpreter, the first line should be

  #!/bin/bash
To use the sh command interpreter (often used for scripts), use first line
  #!/bin/sh
For example, when script
#!/bin/bash
mv * ~/.remove/
is performed, it moves all files in the current working directory into directory .remove in your home directory.


Permissions

To run a script, put it into a file and mark that file as executable. If the file is called rmall, then

  chmod u+x rmall
changes the permissions (called the mode) of file rmall so that the user (that is, you) can execute it. Now command
  ./rmall
runs the script in file rmall.


Parameters

A script can use command-line parameters. Write $1 to refer to the first parameter, $2 to the second, etc. For example, suppose that the following is stored in a file called show.

  #!/bin/sh
  echo $1
  cd $1
  ls
Then, after you have marked show to be executable, command
  ./show 2530
will write
  2530
  …
where the … part is a listing of what is found in directory 2530. That is very similar to what is done by command
  ls 2530