Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to make shell script an executable file in linux

Shulou Source: shulou.com Published: 2022-06-01 05:16:33 10月04日 Update

This article mainly introduces how to make the shell script into an executable file in linux, which can be used for reference by interested friends. I hope you can learn a lot after reading this article.

Create a bash script and use the chmod command to make the script executable without the need for the script to be preceded by a sh or bash command to run it.

Create a 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 using the vim editor and add the following bash script to the file:

[root@localhost ~] # vim hello_script.sh

Here is the content of the script added to the file:

#! / bin/bash echo "Hello World"

After editing, save and exit.

Execute Bash script

There are two ways to run the bash file. The first is by using the bash or sh command. The other is to add executable permissions to the file and run it directly. Let's run the following command to execute the bash script using the 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 already has x executable permissions.

Execute script

After you assign executable permissions to a script, you can run the script without the bash command, as follows:

[root@localhost ~] #. / hello_script.sh Hello World

Real example

In the following example, I will write and execute a bash script to back up from the source directory to the destination directory:

[root@localhost ~] # vim backup_script.sh

Paste the following into the backup_script.sh file.

#! / bin/bash TIME= `date +% Yee% masked% d` DESTINATION=/tmp/backup-$TIME.tar.gz SOURCE=/var/log tar-zcvf $DESTINATION $SOURCE

Save the script file and exit. Add executable permissions to the script file:

[root@localhost ~] # chmod + x backup_script.sh

Run the script:

[root@localhost ~] #. / backup_script.sh

Thank you for reading this article carefully. I hope the article "how to make shell scripts into executable files in linux" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Scripts files commands permissions runs articles content methods values interests at the same time backups more friends source directories directories targets knowledge examples tapes Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Huawei Docker Shulou Information macOS