- How To Run a Script In Linux
- Examples that shows how to run a script in Linux
- How to Create Simple Shell Scripts in Linux
- 1. Create a Simple Shell Script
- 2. Using Conditional Statements to Execute Code
- Example of an if Statement Only
- Example of an if-else Statement
- Example of an if-elif-else Statement
- 3. Using the If Statement with AND Logic
- 5. Using the If Statement with OR Logic
- Use Looping Constructs
- While loop
- For loop
- Bash Positional Parameters
- Shell Command Exit Codes
- Processing Output of Shell Commands within a Script
- If You Appreciate What We Do Here On TecMint, You Should Consider:
How To Run a Script In Linux
H ow do I run a Linux shell script? How can I run a script in Linux operating system using command line options?
By default, the shell script will not run. You need to set execute permission for your shell script. To execute or run script type the following command:
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | None |
Est. reading time | N/A |
chmod +x script-name-here
OR
chmod 0755 script.sh
Next, use the ls command to view permission on the script:
$ ls -l script-name-here
To execute the script, type:
$ ./script-name-here
You can also run a script using any one of the following syntax:
$ /path/to/shell/script/backup.sh
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Run a script called backup.ksh using ksh shell:
$ ksh backup.ksh
To run a script called backup.bash using BASH shell:
$ bash backup.bash
Examples that shows how to run a script in Linux
Create a shell script called hello.sh using a text editor such as vi or gedit/nano:
nano hello.sh
OR
vim hello.sh
Append the following code:
Conclusion
You learned how to write a simple shell script and run a script in Linux operating system with help of chmod and other commands. Please see the following tutorials for more information on bash shell scripting under Linux or Unix-like operating systems:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
this is very good. It’s just missing one thing. the export command should be added in in the
/.bashrc file to survive across sessions.
$ tail -1
or the equivalent for your chosen shell (bs, ksh, tcsh etc …)
Just the solution I needed to figure this out, thanks man! 😀
Nice.
For compiling C prgms,
cc hello.c
./a.out
btw, Why don’t you have categories in WP?
Click on category icon (hint: Bash shell).
Hello Vivek, I was not aware that that image is a category link, too 🙂 It really looks like a post image. I’m referencing this site from time to time, and I’ve learned that you have categories just now! I’d really suggest using a different method for showing categories, unless you want to hide them 🙂 Thanks for the great site.
we can run a script even with out permissions using source command
sourch scriptname.sh
no dear if u want to run script the u hv to give execute permission on that file
like….scriptname.sh
chmod 755 or 777 scriptname.sh
Don’t be a patronizing shit…
hi. i m facing problem to write for setup ip address ,subnet and gateway in linux
kindly suggest me how i do…
if u have the give me idea…
#include
int main()
<
system(“c:\\windows\\your system name\\ip config”);
return 0;
>
Good information. I am trying to run a sql using a shell command.
Please provide the info..
How to run the Unix command only during the even and odd hours only.
Kindly provide the command to incorporate in the script.
Hi,
I am having a problem related to this. I have downloaded an program and it has a GUI written in Java. I need to run the script to launch this program, with “sudo” privileges in order to having it running properly. I don’t want to navigate to the folder where this script is, every time I need it, therefore I first made it executable and added the folder to the PATH. Now, when I write “sudo script-name”, I get “script-name not command found”, if I write only “script-name”, it finds it but it doesn’t run properly. Is there a way to launch a script, that is in the PATH, with sudo privileges? Thank you in advance.
Run it as follows:
Or cd to /home/foo and run:
Thank you. I decide to add it as an alias: “alias script-name=’sudo bash /path/to/script/script-name”
What’s the difference with §. /PATH/TO/TARGET§ and §./PATH/TO/TARGET§ ?
thanx, im learning and your are a good teacher.
Источник
How to Create Simple Shell Scripts in Linux
Creating shell scripts is one of the most essential skills that Linux users should have at the tip of their fingers. Shell scripts play an enormous role in automating repetitive tasks which otherwise would be tedious executing line by line.
In this tutorial, we highlight some of the basic shell scripting operations that every Linux user should have.
1. Create a Simple Shell Script
A shell script is a file that comprises ASCII text. We will start by creating a simple shell script, and to do this, we will use a text editor. There are quite a number of text editors, both command-line and GUI-based. For this guide, we will use the vim editor.
We will start off by creating a simple script that displays “Hello world” when executed.
Paste the following content in the file and save.
Let’s go over the shell script line by line.
- The first line – #!/bin/bash – is known as the shebang header. This is a special construct that indicates what program will be used to interpret the script. In this case, this will be the bash shell indicated by /bin/bash. There are other scripting languages such as Python which is denoted by #!/usr/bin/python3 and Perl whose shebang header is is denoted by #!/usr/bin/perl .
- The second line is a comment. A comment is a statement that describes what a shell script does and is not executed when the script is run. Comments are always preceded by the hash sign # .
- The last line is the command that prints the ‘Hello World’ message on the terminal.
The next step is to make the script executable by assigning execute permission using the chmod command as shown.
Finally, run the shell script using either of the commands:
Create Hello World Shell Script
2. Using Conditional Statements to Execute Code
Like other programming languages, conditional statements are used in bash scripting to make decisions, with only a slight variation in the syntax. We are going to cover the if, if-else, and elif conditional statements.
Example of an if Statement Only
The if statement can be used to test single or multiple conditions. We will start off with the fundamental use of the if statement to test a single condition. The if statement is defined by the if . fi blocks.
Let’s take a look at the shell script below.
The above shell script prompts the user to provide a score that is then stored in a variable x. If the score corresponds to 70, the script returns the output “Good job!”. The comparison operator == is used to test if the score entered, which is stored in the variable x, is equivalent to 100.
if Statement in Shell Script
Other comparison operators you can use include:
- -eq – Equal to
- -ne – Not equal to
- -lt – Less than
- -le – Less than or equal to
- -lt – Less than
- -ge – Greater than or equal to
For example, the if-statement block below prints out ‘Work Harder’ if the input score is any value less than 50.
if Statement in Shell Script
Example of an if-else Statement
For situations where you have 2 possible outcomes: – whether this or that – the if-else statement comes in handy.
The script below reads the input score and checks whether it is greater than or equal to 70.
If the score is greater than or equal to 70, you get a ‘Great job, You passed!’ message. However, if the score falls below 70, the output ‘You failed’ will be printed.
if-else statement in Shell Script
Example of an if-elif-else Statement
In scenarios where there are multiple conditions and different outcomes, the if-elif-else statement is used. This statement takes the following format.
For example, we have a script for a lottery that checks if the number entered is either 90, 60 or 30.
if-elif-else statement
3. Using the If Statement with AND Logic
You can use the if statement alongside the AND logic operator to execute a task if two conditions are satisfied. The && operator is used to denote the AND logic.
5. Using the If Statement with OR Logic
When using the OR logic, that is represented by || symbol, either one of the conditions needs to be satisfied with the script to give the expected results.
If statement with OR logic
Use Looping Constructs
Bash loops allow users to perform a series of tasks until a certain result is achieved. This comes in handy in performing repetitive tasks. In this section, we shall have a peek at some of the loops which you’d also find in other programming languages.
While loop
This is one of the easiest loops to work with. The syntax is quite simple:
The while loop below lists all the numbers from 1 to 10 when executed.
Let’s disscuss the while loop:
The variable counter is initialized to 1. And while the variable is less than or equal to 10, the value of the counter will be incremented until the condition is satisfied. The line echo $counter prints all the numbers from 1 to 10.
While loop in Shell Script
For loop
Like the while loop, a for loop is used to execute code iteratively. I.e. repeat code execution as many times as possible defined by the user.
The for loop below iterates through 1 right through 10 and processes their values on the screen.
For loop in Shell Script
A better way to achieve this is to define a range using the double curly braces < >as shown instead of typing all the numbers.
Bash Positional Parameters
A positional parameter is a special variable that is referenced in the script when values are passed on the shell but cannot be assigned. Positional parameters run from $0 $1 $2 $3 …… to $9. Beyond the $9 value, the parameters have to be enclosed in curly brackets e.g $<10>, $ <11>… and so on.
When executing the script, the first positional parameter which is $0 takes the name of the shell script. The $1 parameter takes the first variable that is passed on the terminal, $2 takes the second, $3 the third and so on.
Let’s create a script test.sh as shown.
Next, execute the script and provide the first and second name as the arguments:
Bash Positional Parameter
From the output, we can see that the first variable that is printed is the name of the shell script, in this case, test.sh. Thereafter, the names are printed out corresponding to the positional parameters defined in the shell script.
Positional parameters are useful in that they help you customize the data being entered instead of explicitly assigning a value to a variable.
Shell Command Exit Codes
Let’s begin by answering a simple question, What is an exit code?
Every command executed on the shell by a user or shell script has an exit status. An exit status is an integer.
An exit status of 0 implies that the command executed successfully without any errors. Anything between 1 to 255 shows that the command failed or did not execute successfully.
To find the exit status of a command, use the $? Shell variable.
An exit status of 1 points to a general error or any impermissible errors such as editing files without sudo permissions.
An exit status of 2 points to incorrect usage of a command or builtin shell variable.
The 127 exit status points to an illegal command which usually yields the ‘command not found’ error.
Find Exit Status of Command
Processing Output of Shell Commands within a Script
In bash scripting, you can store the output of a command in a variable for future use. This is also referred to as shell command substitution and can be achieved in the following ways.
For example, you can store the date command in a variable called today and call the shell script to reveal the current date.
Print Date Using Shell Script
Let’s take another example. Suppose you want to find the valid login users on your Linux system. How would you go about it? First, the list of all the users (both system, process, and login users) is stored in the /etc/passwd file.
To view the file, you’d need to use the cat command. However, to narrow down to log in users, use the grep command to search for users with the /bin/bash attribute and use the cut -c 1-10 command as shown to display the first 10 characters of the names.
We have stored the cat command to the login_users variable.
List Logged in Users
This brings our tutorial on creating simple shell scripts to an end. We hope you found this valuable.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник