Posted under » Linux on 21 October 2009
A shell script is similar to the windows batch file running PowerShell. It will execute commands listed on the text file. Shell scripting is an important part of process automation in Linux. Scripting helps you write a sequence of commands in a file and then execute them. It is powerful when you combine it with cron.
It is also called a bash script. Bash scripts end with a .sh Scripts are also identified with a shebang. Shebang is a combination of bash # and bang ! followed the the bash shell path to the bash interpreter. This is the first line of the script.
To find the path of bash:
$ which bash $ /usr/bin/bash
Example best.sh
#! /usr/bin/bash # Script to print user information who currently login , current date & time # clear echo "Hello $USER" echo "Today is \ ";date echo "Number of user login : \ " ; who | wc -l echo "Calendar" cal exit 0
If you want to create a daemon test.sh
#! /usr/bin/bash
echo "test.service: ## Starting ##" | systemd-cat -p info
while :
do
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
echo "test.service: timestamp ${TIMESTAMP}" | systemd-cat -p info
sleep 60
done
The two echo lines are piped through systemd-cat, a program that takes the output from a program and sends it to the journal. Entries to the journal are given a priority. We're using the -p (priority) option to indicate that our messages are for information (info) only. They're not important errors or warnings. Learn more about journalctl.
In order to run (if not in your home dir), chmod the file to make it executable. Execute it by typing the file name out with its location (relative or full) or type sh in front.
$ chmod 755 test.sh // or chmod u+x test.sh $ ./test.sh $ /var/script/test.sh
Sometimes it is easier to create Bash Alias. If you want to forget the last history
$ history -d $(expr $(history | tail -n 1 | grep -oP '^\s*\d+') - 1);