Simple Scripts and Environment Variables

From docwiki
Revision as of 13:42, 1 April 2020 by Mond (talk | contribs) (Building a Simple Script)
Jump to: navigation, search


Motivation

One of the main advantages of using CLI instead of GUI is that within the CLI it is much easier to automate tasks. All that is needed is to put the commands that you would normally execute in a text file and tell the system that it is executable. This is not meant to be a full fledged course in shell scripting but should only tell you the very basics.

Building a Simple Script

With your text editor of choice generate a text file with the name myscript.sh (in the example below I write vim - but you can use other text editors as well)

$ vim myscript.sh
$ chmod +x  myscript.sh
$ ./myscript.sh

The above creates the script. (For what you type in the script see below), and sets it to be executable (chmod +x). After that you can run the script. When you want to start a script which is not in the PATH where you would normally have your executable files then you need to give the path name. In our case we take the . as the current directory.

What could be in your script?

#!/bin/bash
echo hello world
echo today is $(date)

The first 2 characters of every script need to be #! (pronounced: hash-bang) and after that the path to the executable which processes the script. So you can write your scripts in other languages simply by changing the interpreter there. E.g. python, perl, etc..

Here is a slightly more complex example:

#!/bin/bash
# a loop over 3 words
for k in ene mene muh ; do
  echo $k
done

Where k is a variable. Here it loops over 3 words. You could also loop over all png files in the directory by using for k in *.png. If you just say for k ; do you would loop over the command line arguments given to the script.

Environment Variables