There are many methods to choose from to execute shell scripts in Linux. In this article, I will share with you the specific method of adding shell script execution permissions in Linux.
Create script file
The first step is to create a new file with a .sh extension using the following command:
[root@localhost ~]# touch hello_script.sh
Write a simple script
Open the newly created file with vim editorlinux execution permissionsand add the following bash script to the file:
[root@localhost ~]# vim hello_script.sh
The following is the script content added to the file:
#!/bin/bash echo "Hello World"
After editing, save and exit.
Execute Bash script
There are two ways to run bash files. The first is by using bash or sh commands. Another way is to add executable permissions to the filelinux execution permissions, and you can run it directly. Let us run the following command to execute bash script using bash or sh command.
[root@localhost ~]# sh hello_script.sh Hello World [root@localhost ~]# bash hello_script.sh Hello World
Set executable permissions for script files
The second way to execute a bash script is to set executable permissions.
[root@localhost ~]# chmod +x hello_script.sh
You can see that the hello_script.sh file has been granted executable permissions.
Execute script
After assigning executable permissions to the script, you can run the script directly without the bash command to see what system Linux is, as shown below:
[root@localhost ~]# ./hello_script.sh Hello World
Examples
In the example below android linux, I will compile and execute a bash script to backup from the source directory to the target directory:
[root@localhost ~]# vim backup_script.sh
Paste the following content into the backup_script.sh file.
#!/bin/bash TIME=`date +%Y_%m_%d` DESTINATION=/tmp/backup-$TIME.tar.gz SOURCE=/var/log tar -zcvf $DESTINATION $SOURCE
Save the script file and exit. Add executable permissions to script files:
[root@localhost ~]# chmod +x backup_script.sh
运行脚本:
[root@localhost ~]# ./backup_script.sh
The above is the detailed content of Multiple ways to execute shell scripts in Linux and sharing of specific methods. For more information, please follow other related articles on the PHP Chinese website!