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:
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
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