Ubuntu - Scripting



Since we have the ability to work with the command line which we covered in the previous chapter, it is common to create scripts which can perform simple jobs. Scripting is normally used to automate administrative tasks. Let’s create a simple script using the following steps. The script will be used to display the IP address assigned to the machine.

Step 1 − Open the editor. Just like notepad in Windows, Ubuntu has a text editor. In the search dialog box, enter the keyword of editor. Then double-click on the Text Editor option.

Open Editor

The following editor screen pops up.

Screen Pops Up

Step 2 − Enter the following text in the editor.

originalAddress=@(ifconfig | grep “inet addr” | head –n 1 | cut –d “:” –f 2 | cut –d “ “ –f 1)
 
echo $originalAddress

Step 3 − Save the file as write-ip.sh.

Save File

Now once you have saved the file, we need to assign the file some execute rights. Otherwise, we will not be able to execute the file.

Step 4 − Go to the command prompt, navigate to the Desktop location and issue the following command.

chmod a+x write-ip.sh 

The above command will provide execute permissions to the file.

Execute Permissions

Step 5 − Now, we can execute the file by issuing the following command.

./write-ip.sh

The output will be the IP address assigned to the machine as shown in the following screenshot.

Assign IP Address
Advertisements