Linux Shell Programming for Beginners
Virtualization and cloud computing has made setting up Linux servers easy and available for anyone. At any one time, I manage up to 10 Linux servers between my home lab and cloud-based servers. When I log into a system I need to quickly check system statistics including server name, IP address, disk space, free memory, and logged-in users. I could type each command individually, or create a shell script to run all the commands at once. As a system administrator, learning some basic shell scripting commands will make your life easier.
Linux Command Summary
You will notice that the commands in our shell script are all Linux commands. Shell scripts allow us to run simple Linux commands without the need to learn a programming language. Shell scripts can be incredibly simple like the one in this example, or complex requiring user input, loops, and functions.
Displays current date
Displays IP address
Displays system hardware info
Displays disk information in megabytes
Displays memory information in megabytes
Displays users currently logged in.
Clears the screen
Prints information to the screen
Getting started with shell scripting is pretty easy. There are only a couple of things you need to know to write your first script. You can use any Linux command you execute on the command line in your script. Besides regular Linux commands the only other important line is the first one:
“#!/bin/bash” is an operator called a shebang which directs the script to the interpreter's location, in our case the script gets directed to the bourne-shell. The rest of the script is all Linux commands.
From your home directory, use your favorite editor to enter the following shell script.
#!/bin/bash clear echo "Starting system information check." echo " " date echo -n "Server: " hostname echo -n "IP Address: " hostname -I echo " " lsb_release -a echo " " df -h echo "---------" echo "Memory: " free --mega echo "--------------------------" echo "Logged in users: " w echo " " echo "End system status."
Following Unix naming conventions, save the file with a .sh extension to identify it as a shell script. In this example, our filename is mystatus.sh.
Making Our Script Executable
Before running shell scripts you need to change the permissions on the file so that they are executable.
Use the chmod command to make this file executable.
$ chmod 755 mystatus.sh
Confirm the file permissions with $ ls -alg mystatus.sh
Run the Program
Assuming that file permissions are correct and there are no typos, run or execute the shell script by typing its filename:
You can add, delete, or modify any of the commands in this script to suit your environment. I copy this file to each machine I administer so I can get a quick status update when moving between systems.