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
- Use a text editor such as vi or nano to write Linux shell script: vi script-name
- Make shell script executable by typing chmod +x script-name
- 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:
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:
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:
You can use full path too:
So if test.sh stored in /home/vivek/, run:
Understanding test.sh shell script
The first line is:
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.
For more information see my Linux Shell Scripting Tutorial Wiki