DEV Community

iainrough
iainrough

Posted on

3 2

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

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay