In this section, I will introduce the useful automation techniques while developing software. We have to deal with many circumstances, such as how to execute a program after boot automatically or in specific time regularly.
Environmental path
Besides the buit-in commands, we can define our command which executing a shell script in every working directory. For example, we want to type bobo
and echo Hello bobo
in terminal. First, create a directory that place the shell script with echo Hello bobo
.
Now if we execute the script directly. The command will not be found. This is because we can not see the directory in environmental path (Use echo $PATH
to check it). Hence, if we add the directory to the environmental path, the script can be execute in every place.
However, if we open another terminal, the environmental path will not be seen in it. Thus, if we want to set the directory in environmental path permanently, we have to execute the setting command during login the desktop.
~/.profile: auto execution while login
The ~/.profile
is a shell script that will be auto executed when login the desktop everytime. Thus, we can add some command to set the permanent environmental path.
Add the command export PATH=$PATH:<your_path>
at the end of ~/.profile
. The export
command ensures the path can be take into effect in different terminals. The source
command is to refresh the script immediately without login again. Therefore, we can see the modified environmental path.
Now, login again and type the command directly. You will find the command can be execute in every path without specify the directory.
/etc/crontab: auto execute regularly
Many tasks needs to be executed regularly and automatically, such as reboot a server, upload data to a server, generate a system report, and so on. The /etc/crontab
is a text file that helps you to do such requirement. However, one needs the super user permission to access that.
1 | sudo vim /etc/crontab |
You can see there are several tasks in default. The first five columns refers to minute, hour, day-of-month,
month-of-year and day-of-week. The * in each column means “every”. For instance, 0 4 * * *
means executing the command at 4 o’clock every day. The sixth column specifies who execute the command, and the last column is the command.
Moreover, if we want to execute a command in a new thread, that is, continue running regardless of the current task is finished, we can add &
at the end of the command. It is both valid in crontab and every shell script.
Sudo without typing password
To execute program automatically, entering the password manually for getting permission is not allowed. The simplest way to solve that is typing password in command line.
1 | echo <password> | sudo -S <command> |