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:~$
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.
#!/bin/bash# Check we have a parameterif["$1"=""]then
echo"syntax: old {filename}"fi# Copy the file as .oldnewFileName="$1.old"echo$newFileNamecp$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
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.
Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.
Top comments (0)