DEV Community

loading...

if... then... elif.. else - Adventures in WSL2 Scripting #1

iainrough
・2 min read

First up some basics

WSL2 with ubuntu 20.04

A lot of the logic in the scripts I write rely on bash's if.. then.. else. The basic syntax of the statement is as follows:

 
if [ {statement} {operator} {value} ]
then
# do something here
elif [ {statement} {operator} {value} ]
# else if do something
else
# do something else
fi # this is just if spelled backwards.
The syntax.

Why the square brackets?

[...] tells bash to evaluate the command and return 0 or 1 for the conditional expression inside the square brackets.

    test and [ evaluate conditional expressions using a set of 
    rules based on the number of arguments.
source: `man test`.

tldr; ensure things evaluate correctly.

Muting the output

> is used to redirect the output of a command somewhere.

   dev@Dark-Matter:~$ cp file1 file2
   cp: cannot stat 'file1': No such file or directory
   dev@Dark-Matter:~$ cp file1 file2 >&- 2>&-
   dev@Dark-Matter:~$
Enter fullscreen mode Exit fullscreen mode
Example with and without redirect.

Getting exit code from a command

$? returns the success of the previous command, 0 for success and >= 1 for failure. Lets look at the previous example and see what the output is.

   dev@Dark-Matter:~$ cp file1 file2 >&- 2>&-
   dev@Dark-Matter:~$ echo $?
   1
Enter fullscreen mode Exit fullscreen mode
Getting the exit code from a command.

Simple example

   #!/bin/bash
   cp file1 file2 >&- 2>&-
   if ["$?" = "1" ]
   then
      touch file1
      cp file1 file2
   else
     echo "File copied to file 2" 
   fi

Enter fullscreen mode Exit fullscreen mode
Simple example.

Something useful

#!/bin/bash
# Check we have a parameter

if [ "$1" = "" ]
then
   echo "syntax: old {filename}"
fi

# Copy the file as .old
newFileName="$1.old"
echo $newFileName
cp $1 $newFileName >&- 2>&-

if [ "$?" = "0" ]
then
      echo "File has aged and has had '.old' appended to it"
      exit 0
else
     echo "File has not been born yet or you do not have parental rights to the file."
     exit 1
fi

Enter fullscreen mode Exit fullscreen mode
Simple example.

Discussion (0)