DEV Community

Marc Katz
Marc Katz

Posted on

Some basic bash tips

When using a Unix terminal, executing commands can be complicated and time consuming to do manually. However, with the power of bash scripting they can all be automated and simplified. Here are a few basic tips you can use to spice up your command line experience:

Making a bash script

The first thing to do is to create a script file. This is a file with the suffix .sh. These files can be run from the command line with the command bash <filename.sh>. To the start of the file, add #!/bin/bash to tell the terminal how to run it.
In this file, you can do anything else you can in the command line, such as ls (list files in the directory), echo (print to the terminal), cd (change directory), and cat (write to file).

Variables and input

Like in other languages, you can create variables in a bash script. It's extremely simple, just <variable name> = <value>. If you want to access the variable later on, you can do so with $<variable name>. For example,

read user_input
echo $user_input
Enter fullscreen mode Exit fullscreen mode

will simply print whatever the user typed into the command line back out at them.
For input, there are two main waits you can get it. One way is with read, which takes in input typed by the user in the command line. The other is with arguments, which can be passed when running the script initially. To access the arguments, use $<n>, where n is the nth argument passed.

Basic logic

The next step to make these scripts more programmable is with logic. The first main piece of logic is with if/elif/else statements. The main syntax is:

if [[<condition>]]; then
    <code>
elif [[<another condition>]]; then
    <code>
else
    <code>
fi
Enter fullscreen mode Exit fullscreen mode

Don't forget to add fi to the end to end the if statement! You can also add as my elif statements as you need.
For the conditions, some basic logic operators include -a <filename> (returns true if the file exists), -s <filename> (returns true if the file exists and isn't empty), and -z <string> (returns true if the string is empty, -n is the opposite). For and, or, and not, you can use &&/-a, ||/-o, and ! respectively.

Loops

Lastly, we can add loops to the script. For a basic while loop, write

while [[<condition>]]; do
   <code>
done
Enter fullscreen mode Exit fullscreen mode

For a for loops, do

for <var> in {<start>..<end>} do
   <code>
done
Enter fullscreen mode Exit fullscreen mode

This will execute <code> <end>-<start> times, with the value stored in <var>

Top comments (0)