Categories
Linux Tutorial Series

Linux Tutorial Series – 193 – Command substitution

Here is the video version, if you prefer it:

You can take a result of a command and store it in a variable or use the result of that first command as an argument for another command. This is called command substitution. (Ward, 2014)⁠

Here is an example of command substitution in a sample script:

#!/bin/bash

LINES=$(grep 'a' aba.txt)

for word in $LINES

do

echo $word

done

We first take every line that has the character a in the file aba.txt and then we store it in the variable LINES. Then we iterate over each word in the variable LINES and we print it. Why does LINES contain words, not lines? It contains lines indeed, but words that make up those lines are separated by a space (you can see so yourself by putting echo $LINES just before the for loop) and since each space is interpreted as a delimiter in a sequence, we get individual words.

Here is the output (along with aba.txt contents):

mislav@mislavovo-racunalo:~/Linux_folder$ cat aba.txt

Mustard is how we transfer wealth

Some stuff Abba Mustard

Mustard Mustard

Mustard Mustard

It's the Mustard

In the Rich Man's World

AB

Mustard is how we transfer wealth

Ab

aB

ab

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh

Mustard

is

how

we

transfer

wealth

A simple example of using the result of the first command as an input to another command is echo $(ls). We use the output of ls and we echo it.

Thank you for reading!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 263-264

Categories
Linux Tutorial Series

Linux Tutorial Series – 192 – while and until loops

Here is the video version, if you prefer it:

while and until loops are used for iteration, the same as for loops. However, I won’t teach you these. Why? Because, as (Ward, 2014)⁠ says, if you ever need a while loop (or an until loop), it’s a good time to move to another programming language. I agree.

I will tell you that (“Bash While Loop Examples,” n.d.)⁠ and a Google search will teach you, if you really must use them. But again, I will repeat myself: If you need to use a while or an until loop, switch to another programming language.

Thank you for reading!

References

Bash While Loop Examples. (n.d.). Retrieved February 22, 2020, from https://www.cyberciti.biz/faq/bash-while-loop/

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 262-263

Categories
Linux Tutorial Series

Linux Tutorial Series – 191 – for loops

Here is the video version, if you prefer it:

for loops are used for iterating. Iterating means going over a sequence of values.

Here is an example of a for loop, modeled after (“Bash For Loop Examples,” n.d.)⁠.

#!/bin/bash

for i in 1 2 3 4 5

do

echo $i

done

This will produce the following output:

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh

1

2

3

4

5

What just happened? The variable i first took on the value of 1 (the first element in the sequence). Then it echoed its value. Then variable i took the next value in the sequence (the value after the value it currently had). So i was 2. Then 2 got outputted – and so on until the end of the sequence.

You can specify numerical sequences more easily (the above one could have been written as {1..5}) and you can iterate over other sequences (not just numbers, but other things – files for example). I leave you to consult the reference and Google for some further examples.

Hope you learned something useful!

References

Bash For Loop Examples. (n.d.). Retrieved February 22, 2020, from https://www.cyberciti.biz/faq/bash-for-loop/

Categories
Linux Tutorial Series

Linux Tutorial Series – 190 – case statement

Here is the video version, if you prefer it:

Today let’s talk about the case statement. case statement is used to replace a lot of elif statements. Here is our entire script with the same functionality it had before, rewritten using a case statement:

#!/bin/bash

case $1 in

'Hello')

echo 'Hello back to you!'

;;

'Hi')

echo 'Hi!'

;;

*)

echo 'You are rude.'

;;

esac

Here is how the case statement works:

  1. You tell case which argument you are testing (more specifically, pattern matching) – we are testing the argument passed to the script in the first position ($1)
  2. case goes through the list of patterns (each pattern ends in a )) and if it finds a matching pattern, the code between the ) and the ;; is executed and then it skips to esac
  3. esac denotes the end of the case statement

The case statement does not evaluate any exit codes, it just matches patterns.

Here are some things to note: (Ward, 2014)⁠

  • multiple strings can be matched with | – if I put ‘Hi!’|’Hi’ I would match both “Hi!” and “Hi” and that line would look like 'Hi!'| ‘Hi’)
  • * matches a case which is unmatched by any other case

Hope you found this useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 261-262

Categories
Linux Tutorial Series

Linux Tutorial Series – 189 – Testing conditions

Here is the video version, if you prefer it:

In our script, we have tested if our first argument equals a certain string, that is:

[ "$1" = 'Hello' ]

there are other tests as well. You can test files (for example, if a file is a regular file), integers and strings. I won’t cover that here and will leave you this resource to look at if you want to learn more about these tests: (“Chapter 7. Tests,” n.d.)⁠ Relevant sections are 7.2 and 7.3.

But remember, no matter what test you are using, the gist of it is: “If this is true (if the exit code is 0) then do this, if not, do the other thing”.

Hope you learned something useful!

References

Chapter 7. Tests. (n.d.). Retrieved February 22, 2020, from https://www.tldp.org/LDP/abs/html/tests.html. Sections 7.2 and 7.3

Categories
Linux Tutorial Series

Linux Tutorial Series – 188.1 – Logical operators usage in tests

Here is the video version, if you prefer it:

We talked about logical operators (&& (and) and || (or)) and got to understand how they work. You can also use them in tests.

If you use &&, then if the first test is not successful, its exit code is used for the if statement and if the first test is successful, then the exit code of the second test is used for the if statement. If you use ||, if the first test is not successful, the second test’s exit code is used as the exit code for the if statement and if the first test is successful, the first test’s exit code is used as the exit code for the if statement. (Ward, 2014)⁠

For example, you can write:

if [ “$1” = ‘Hi’ ] || [ “$1” = ‘Hello’ ]

if you were to test if the first argument is either “Hi” or “Hello”.

Think of it like this: && says “Both of the conditions have to be true” while || says “Only one of the conditions must be true”. This holds because only the exit value of 0 is used to indicate success. Re-read the second paragraph and make sure you understand this.

You can combine more than just two conditions with logical operators.

Hope you learned something useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Page 258

Categories
Linux Tutorial Series

Linux Tutorial Series – 188 – Logical operators

Here is the video version, if you prefer it:

Let’s talk about logical operators outside of the context of shell scripts, at first.

If I run two commands like this:

touch someFile && emacs someFile

what would happen is that I would create a file named someFile and then I would immediately open it with Emacs (if you don’t have Emacs, you can use less). However, try this:

mislav@mislavovo-racunalo:~/Linux_folder$ ls -l nonExistentFile && emacs someFile

ls: cannot access 'nonExistentFile': No such file or directory

What happened here is that we tried to use ls on a non existent file and we got an error message. But our Emacs didn’t open up as well. What is happening here?

See, when you use the && operator (also known as the “and” operator) you are saying “Execute the first command and then, if it succeeds, execute the second command”. How does the shell know if a command executed successfully? Why, by exit code, of course! (Ward, 2014)⁠

When a command is successful, its exit code is 0. && says “I will execute the second command only if the exit code of the first command (to the left of the && sign) is 0”. ||, another logical operator, says just the opposite: “I will execute the second command only if the exit code of the first command (to the left of the || sign) is not 0”. You can remember it like this, but this makes more sense if you know about logical gates, which you don’t need to to understand Linux, so I won’t explain those.

So if I write:

mislav@mislavovo-racunalo:~/Linux_folder$ ls -l nonExistentFile || emacs someFile

this actually opens up Emacs, because || works in the way I described above.

Hope you learned something useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Page 258

Categories
Linux Tutorial Series

Linux Tutorial Series – 187 – Elif (else if)

Here is the video version, if you prefer it:

Checking only one condition in a conditional is not the only thing we can do. We can check multiple conditions, using elif. Here is how to use elif:

#!/bin/bash

if [ "$1" = ‘Hello’ ]

then

echo 'Hello back to you!'

elif [ "$1" = ‘Hi’ ]

then

echo 'Hi!'

else

echo 'You are rude.'

fi

This is our entire shell script with an added elif, modeled after (Ward, 2014)⁠. Let’s look at its output:

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh Hello

Hello back to you!

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh Hi

Hi!

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh

You are rude.

You can use elif to test for multiple conditions. But there is also another construct, called case, which is more appropriate than just a bunch of elifs. We will talk about case later on.

Hope you learned something new!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Page 258

Categories
Linux Tutorial Series

Linux Tutorial Series – 186 – The else statement

Here is the video version, if you prefer it:

The else statement in combination with the if statement is used to tell the following: “If this condition is true do this, if this condition is not true, do that”. That’s pretty much the gist of it.

Below is the entire shell script (with the else statement), modeled after (Ward, 2014)⁠:

#!/bin/bash

if [ “$1” = ‘Hello’ ]

then

echo 'Hello back to you!'

else

echo 'You are rude.'

fi

And let’s run this script with the first argument being Hello and then it being something different:

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh Hello

Hello back to you!

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh argument1

You are rude.

What is happening here? We are testing if the first argument to our script is Hello. If it is, we echo Hello back to you! and if it is not, we echo You are rude.

What happens is the following:

  1. The test in the if condition is tested – that is, we check if $1 really equals Hello.
  2. If the test from step 1 is true (meaning that the exit code is 0), we execute the code starting at then until else – that is, we echo “Hello back to you!”
  3. If the test from step 1 is false (meaning that the exit code is not 0), we execute the code starting at else until fi – that is, we echo “You are rude.”

This process above follows the logic of: “If the condition is true, then this, if not (else), then the other thing”.

Hope you learned something useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 256-257

Categories
Linux Tutorial Series

Linux Tutorial Series – 185 – The if statement

Here is the video version, if you prefer it:

The if statement allows us to test for a condition and execute a certain set of commands based on the result of that test. (“If Statements!,” n.d.)⁠

An example script:

#!/bin/bash

if [ "$1" = 'Hello' ]

then

echo 'Hello back to you!'

fi

What is happening here? We are testing if the first argument to our script is Hello. If it is, we echo Hello back to you! and if it is not, we don’t do anything.

More technically, the [ is a command that performs tests for Unix conditionals. (Ward, 2014)⁠ The if, then and fi are shell keywords and everything else is a command. So what happens is that we check if the first argument to our shell script is indeed equal to Hello. If it is, then we echo Hello back to you!. If it is not, we don’t echo out anything.

A detail – the [ command returns an exit code. If the exit code is 0 (as we learned) that means that the check went well and we go on to echo Hello back to you! and if the exit code is non-zero we know that something went wrong and we don’t echo out anything.

Another detail: why did we surround the $1 in quotes above? Because if we don’t pass the first argument (it is empty), we get an error like so:

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript2.sh

./tutorialScript2.sh: line 2: [: =: unary operator expected

because we don’t supply anything for the missing argument and then we have a gap between the [ and the =. However, when we surround the argument with quotes and don’t supply the argument, we get a so-called empty string (meaning empty sequence of characters). If we use the quotes, we don’t get that error.

Hope you learned something useful!

References

If Statements! (n.d.). Retrieved March 7, 2020, from https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 256-257