create and run a shell

The shell language is a high level programming language. It is more removed from system and memory processes than lower level languages. This basically means that it has commands and functions to perform tasks that would otherwise take a lot of code to execute in lower level languages like C or assembly language.Shell scripts can make use of variables, if-then statements, loops, and pipes (see below).

What can a shell script do?

Shell scripts are great if you need to enter long sequences of commands into the command line to do something. Most operations can be accomplished with a single command if you know how to write a shell script for it. Some things they can be used to do:

  • Control what happens when the computer boots up
  • Start applications when an event occurs
  • Use the output of one command as the input for another command
  • Batch rename and move files
  • Batch convert file formats

One very useful feature of shell scripts is the ability to create pipes. A pipe allows the output of one command to be forwarded to the input of the next command. Pipes can be used with as many commands as you want. The basic syntax for a pipe is:

command 1 | command 2

Here are the ways of connecting commands

  • A; Run A and then B, regardless of success of A
  • A && B Run B if A succeeded
  • A || B Run B if A failed
  • A & Run A in background

How to create and run a shell script

Shell scripts are simply an executable text file with the extension “.sh“. In this example we will write a simple “hello world” script.

To begin, log in to your Raspberry Pi, and navigate to the directory where you will save the shell script. Then enter sudo nano hello-world.sh at the command prompt to open the nano text editor and create a new file named hello-world.sh. Now, enter this code into the nano text editor:

1
2
#!/bin/bash</code>
echo "Hello World!"

The first line of this program, #!/bin/sh, is called a shebang. This tells the BASH shell to execute the commands in the script.

Exit and save the file in nano by pressing Ctrl-X to save and exit.

Next, we will need to make the hello-world.sh file executable. To do this, enter sudo chmod +x hello-world.sh at the command prompt.

Now that our shell script is executable we can run it. Navigate to the directory where the file is saved, and enter either sh hello-world.sh or ./hello-world.sh.

The words “Hello World!” will be printed to the line below the command prompt.

This “hello world” script isn’t particularly useful, but it will show you the basics of how to create and run a shell script.

If you have any questions or problems with anything in this post, please let me know in the comments! Thanks for reading, and if you know anyone that could benefit from this information, please share it!

Leave a Reply

Your email address will not be published. Required fields are marked *