Skip to content

Latest commit

 

History

History
69 lines (49 loc) · 2.6 KB

File metadata and controls

69 lines (49 loc) · 2.6 KB

Scripting with Bash

In addition to being a shell, Bash is also a moderately powerful programming language. Though its syntax is a little unintuitive at times, Bash can be a practical and useful choice for quick scripts.

Multiple lines and comments

We can use ; to separate two commands to be run in succession. Note that the second command will run even if the first one fails.

As mentioned earlier in the workshop, any line beginning with # will not be evaluated by Bash.

variables

Bash supports variables, set through the syntax variable=value.

We can substitute a variable for its value with the expression $variable.

if statements

If statements in bash usually take the following form:

if condition; then
    command
fi

We can have else if statements with elif.

Our condition can be any program, as all programs return an exit code. However, we will often instead use the [] construct, which can evaluate some conditions for us.

  • [ string == string ]: checks for equality
  • [ -f path ]: true if path is a (regular) file
  • [ file1 -nt file2 ]: true if file1 is newer

Loops

There are a few types of loops in bash. The most important are for loops and while loops.

while loops have the following form:

while condition; do
    commands
done

for loops have the form:

for instance in variables; do
    commands
done

Within our commands, we can use $instance to get the value of our current variable.

Our variables can be any set of strings. for file in ./* would loop over all the files in our current directory.

We can get a range of numbers with {start..end}. Try echo {1..10}!

Scripts

Once we have a few useful commands that we want to reuse, we can store them in a script file, to be used later. Usually, we want to be able to run our script directly as an executable. For this to work, we put the following line at the beginning of our script file:

#!/bin/bash

This is a shebang, and it tells our operating system to use bash to evaluate the file. Note that as above, bash itself does not evaluate the shebang, since it starts with a #.

Often we want to have some input to our scripts—like arguments to programs. With the positional parameters $0, $1, etc, we can access these inputs as variables in our script.

Command substitutions

To use the output of a command as a variable in Bash, use $(command).

Exercise

Make a loop to print out the numbers 1 to 100.

Now, your final project: make a program to list the contents of every file in your directory. Save it as a script and test it in multiple directories.