Writing Scripts

Instead of running a single command at a time, you can combine multiple commands into a file to create a script. Scripts can simplify multi-step processes into a single invocation, saving you time in the long-run.

Writing a script is as simple as writing a file. Usually, we make the first line of the script #!/bin/bash to tell the shell to use bash when running the script.

You can create variables in a bash script using the = operator. So to make a variable named myname, you'd write myname="Allen". To use the variable later in the script, you'd prefix it with a $. For example, $myname.

You can also ask for a user's input and store that into a variable by using the read command. Preface it with echo "question?" to give context for what the user is inputting. For example:

echo "What is your name?"
read name

echo "Hello, $name"

You can run shell commands inside of a script and store their results in a variable. To do so, you wrap the command with $(). For example, to get the size of a file and store it in a variable, you'd do file_size = $(du file).

Knowing this, let's create a script that looks through the files in a directory, and moves any files above a certain size to a new folder. Name it sizewatcher.sh

#!/bin/bash

# Make variables for directory to loop through
# and directory where files should be moved.
directory="/home/asoberan/unixclass"
new_directory="/home/asoberan/bigfiles"

# If the new directory doesn't exist, then
# create the directory
if [ ! -d $new_directory]; then
    mkdir $new_directory;
fi;

# Loop through the files in the directory.
# Store the size of the file (in KB), in
# file_size. If the file size is greater
# than 400000 KB, move the file to the
# new directory 
for file in $(ls $directory);
do
    file_size=$(du $file | cut -f1);
    if [ $file_size -gt "400000" ]; then
        mv $file $new_directory;
    fi;
done;

Once you've created and saved this file, make sure to modify its permissions to let it be executed. An easy way of doing this is running the following command:

Then run the script:

Let's create another script that asks a user for a directory, then sorts the files in that directory into folders that correspond to the year and month that the file was created. Name it sorter.sh:

Make it executable and then run it.

Last updated

Was this helpful?