Blog

03/06/2019

How to run shell script in Linux



I am a new Linux system user. How do I run shell script in Linux? How do you execute .sh file in Linux?

Introduction – Bash is the shell, or command language interpreter, for the Linux operating system. The name is an acronym for the Bourne-Again SHell.

How to run shell script in Linux

  1. Use a text editor such as vi or nano to write Linux shell script: vi script-name
  2. Make shell script executable by typing chmod +x script-name
  3. Run Linux shell script by typing “./script-name” OR “bash script-name

Let us see all examples and usage in details.

Step 1. Create a shell script

Type nano command or vi command to create a new shell script named test.sh:
vi test.sh
Append the following text. Press ESC and type I to insert text:

!/bin/bash
echo "Hello, $USER"
echo "Today is $(date)"
echo "Bye"

To save a file, press ESC key and type 😡.

Step 2. Run the shell script on Linux

Try to run it:
./test.sh
Sample outputs:

bash: ./test.sh: Permission denied

The command ./test.sh displayed an error message on the screen. It will not run script since you have not set execute permission for your script test.sh.

Step 3. How to execute test.sh program

Run the following command to set up executable permission on test.sh script:
chmod +x test.sh
Run your script:
./test.sh
You can use full path too:
/path/to/test.sh
So if test.sh stored in /home/vivek/, run:
/home/vivek/test.sh

Understanding test.sh shell script

The first line is:
#!/bin/bash
The #! syntax used in shell scripts to indicate an interpreter for execution. It is called a shebang or a “bang” line. All scripts under Linux execute using the interpreter specified on a first line. The second line display Hello message to user:
echo "Hello, $USER"
The $USER is a shell variable.

Conclusion

For more information see my Linux Shell Scripting Tutorial Wiki

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...