| Home | Notes | Github |
|---|
Written: 05-Mar-2022
So here’s some stuff for writing scripts. The language here is
bash1 if you’re looking up help on the
internet.
Scrips are great because you can write more complex commands easier, but fundamentally all of this can be pasted into the command line, line by line. It’s just not so fun.
The start of your script should (it will probably work without it) start:
#!/bin/bashThis is so the computer knows what language to run.
Then you can start writing the functionality. Functionality is up to you, but here’s some useful bits
for LoopTo loop over files in a directory:
for f in $FILES
do
# Do something here
echo "Reading filename: $f"
doneTo loop over the lines of a file use (useful if there are spaces in a list of filenames):
while IFS= read -r line
do
# Doing something on each line
echo "Text read from file: $line"
done < my_filename.txtif Statementif [ expression ]
then
Statement(s) for true
else
Statement(s) for false
fiCheck two numbers are equal
[ "$a" -eq "$b" ]Check two strings are equal
[ "$str1" = "$str2" ]This got me alot as a beginner. Hopefully it won’t get you too much.
The main fix was to change the IFS variable by adding the
line below to the top of your script.
IFS=$'\n'I’ve heard it might be hacky, but it works well enough for me.
$# = Number of Arguments$0 = 0th Argument a.k.a. the function name.$1 = 1st ArgumentThere’s many ways to provide for user input. More often than not a
basic [y/n] will suffice:
read -r -p "Are you sure? [y/N] " response
case "$response" in
[yY][eE][sS]|[yY])
do_something
;;
*)
do_something_else
;;
esacI’ve also used this tutorial for help. This can progress into other full blown terminal user interfaces, but for simplicity stick to this or basic multiple choice.
find UsageVery useful for finding files (very surprising). Mainly I use it as
an alternative to ls | grep, as shellcheck
tells me off for that kind of behaviour.
Basic Usage:
find {dir} {comand}I like to search by regex, for example, searching for pictures:
find . -iregex '.*\.\(png\|jpg\)'find in current directory (.) with the
regex2 for a file with any name length
engin in .jpg or .png3.
For all this and more in a condensed format see the Scripting Cheat Sheet.