How to run sh script ubuntu

How to run sh script ubuntu

How to run sh script ubuntu

В данной статье пойдет речь о том, как запускать сценарии командной оболочки (shell скрипты) в Ubuntu.

Что такое sh скрипт

Подробнее о сценарии командной оболочки можно прочесть в Wikipedia: Сценарий командной строки.

В такой файл мы можем вписать все команды, которые выполняем в терминале, то есть, которые исполняются командной оболочкой нашей системы.

Как запускать sh скрипты в командной строке.

Запускать скрипты sh из командной строки легко.

1. Сделать файл скрипта исполняемым (если он еще таковым не является):

2. Запускаем скрипт, просто указав путь до него:

Если скрипт находится в текущей директории, то нужно указать ./ перед именем файла скрипта:

Иногда требуются права суперпользователя для запуска скрипта, тогда просто перед скриптом пишем команду sudo:

Можно запускать скрипты, непосредственно указывая интерпретатор: sh, bash и другие:

Но не советую так делать на постоянной основе.

Как запустить sh в файловом менеджере Ubuntu (Nautilus)

В файловом менеджере (Nautilus) Ubuntu sh скрипты запускаются двойным кликом по файлу:

Решаем проблему файлового менеджера Ubuntu при запуске скриптов sh

По умолчанию, после установки системы Ubuntu, если вы попытаетесь выполнить скрипт двойным кликом, то файл у вас откроется в текстовом редакторе:

Чтобы решить эту проблему, открываем «Параметры», переходим на вкладку «Поведение», в пункте «Исполняемые текстовые файлы» выбираем «Спросить что делать» или «Запустить»:

Разница их в том, что при выборе пункта «Спросить что делать», будет выбор в каком режиме запустить скрипт:

Для меня это наиболее удобный пункт, так как скрипт можно запустить в терминале, в графическом режиме или отредактировать в текстовом редакторе.

Как сделать так, чтобы терминал не закрывался после завершения sh скрипта в Ubuntu.

Когда мы запускам какой-либо скрипт из файлового менеджера, выбрав «Запустить в терминале»:

У нас откроется окно терминала. Но после выполнения всех команд, описанных в sh скрипте, окно терминала закроется. В результате, мы не может просмотреть лог (историю) выполнения.

Чтобы решить эту проблему, переходим в «Параметры» терминала. В параметрах выбираем наш профиль и переходим на вкладку «Команда», в пункте «При выходе из команды» выбираем «Держать терминал открытым»:

Ubuntu Documentation

Bash scripting is one of the easiest types of scripting to learn, and is best compared to Windows Batch scripting. Bash is very flexible, and has many advanced features that you won’t see in batch scripts.

However if you are a ‘non-computer-savvy’ person that won’t mean a thing to you. Bash is the language that you will learn to love as much of everyday Ubuntu life is done/can be done using the Terminal. You will soon learn that most things can be done through both GUI (Graphical User Interface) and CLI (Command Line Interface), however some things are more easily achieved from one or the other. For example, changing file permissions of a folder and all its sub folders is more easily achieved using cli instead gui.

NOTE: Text that is inside the box are to be entered into a terminal as follows:

You can also just copy and paste if needed.

Intro

In this document we will discuss useful everyday commands, as well as going a bit more in depth into scripting and semi-advanced features of Bash. Bash is not only used to run programs and applications, but it can also be used to write programs or scripts.

Along with many other things, the list above will be the commands we will discuss.

Commands

Creating folders

Creating folders can be done simply in the file manager nautilus by right clicking and selecting ‘Create Folder’, but if you want to do this from a cli environment you would type the following in the terminal:

the mkdir (make directory) command creates the folder then the file path tells it where to create the folder.

Deleting files

Deleting files are done with the rm command as follows:

the rm (remove) command is used to remove anything through a cli environment.

Deleting folders and their sub-folders

The command you are about to read can potentially (if used incorrectly) destroy your system!

This command is slightly different to the one before, it uses two options ‘-r’ which means recursive (will delete the folder and all sub-folders) and ‘-f’ means force (will not ask for your permission). This command is perfectly fine for deleting a dir and all its sub-dirs. The next commands should !!**!!NEVER!!**!! be run. Unless you want to say goodbye to your system.

This will delete everything from your root folder downwards, which if you did a standard install would be everything.

Running commands as root

When working on the command line, you usually want to work with the default permissions. This way you insure that you won’t accidentally break anything belonging to the system or other users, so long as the system and other users haven’t altered their file permissions. Yet there will be times when you wish to copy a file to a system folder (like /usr/local/bin) to make it available to all users of the system. Only the system administrator (i.e. the user ‘root’) should have permission to alter the contents of system directories like /usr/local/bin. Therefore trying to copy a file (like a program downloaded from the Internet) into that folder is forbidden by default.

Since it would be very tedious to always login as root to do administrative work (in fact you should avoid logging in as root with a graphical desktop) you can use the sudo program to execute a single command as root.

The default Ubuntu installation is configured so that the user who was created during system installation is allowed to use this command. It will prompt for the password and execute the command as the root user.

Opening GUI applications as root

Sometimes you will want to edit a config file in your root folder, in order to save changes to this file you need root privileges so we need to open our text editor as root. All you will need is just sudo or pkexec to show a gui password popup.

Note a lot of kde apps will not work like kate or dolphin.

Backing up your files

To create a backup of a file, we’re going to use the cp (copy) command. The basic syntax for cp is as follows:

This will copy the ‘source_file’ to the ‘dest_file’. Now, using the previous example, we want to backup ‘/path/to/conf_file.txt’. To accomplish this, we type the following:

That’s fine and dandy, but what if I want to copy my file to another directory? Well that’s just as easy. Let’s say instead of copying /path/to/conf_file.txt to the /path/to/ directory, you want to copy it to a directory where you store all of your backup files, say /my/backup/folder/. In order to accomplish this you would type:

***This is a typical safety measure that has saved many users in the past from a complete disaster.***

Okay, so we know how to copy a file: a) to a different filename and b) to a different folder. But how do we copy entire directories?

Backing up your Directories

To backup one directory to another, we introduce cp -r (recursive) option. The basic syntax is as follow:

So if we wanted to copy all of the contents of our /path/to/ folder to our /my/backup/folder, we would type the following:

Checking system performance

If your computer starts to lag, you can see which applications are using the most CPU power with this command:

This is generally the same information given as the GUI application ‘System Monitor’.

Check Devices

If a USB device stops working, you may want to see if it is still connected/detected. To check if a device is connected/detected, type the following:

As PCI devices are checked with:

Show network Information

To see the status of your network connection, use the command:

This command will show you your ip, what type of connection you are using, etc.

Show wireless information

Like the command ip stated above, you can use iwconfig to check the settings of your wireless connection without editing anything. In a terminal enter:

This also shows packets sent/received.

Scripting

NOTE: The commands given in the scripting section are to be put into the text editor and not in the terminal unless instructed otherwise.

The first line of the script just defines which interpreter to use. NOTE: There is no leading whitespace before #!/bin/bash. That’s it, simple as that. To run a bash script you first have to have the correct file permissions. We do this with chmod command in terminal (change mode) as follows:

This will give the file the appropriate permissions so that it can be executed. Now open a terminal and run the script like this:

Hopefully you should have seen it print Hello, World onto your screen. If so well done! That is your first Bash script.

TIP If you type:

You will see the directory that you are currently working in (pwd stands for ‘print working directory’). If your current working directory is /where/i/saved/it/, then you can shorten the above command to:

Now, lets get to more interesting aspects of Bash programming, Variables!

Variables

Variables basically store information. You set variables like this using text editor:

‘var’ can be anything you want as long as it doesn’t begin with a number. «FOO» can be anything you want.

To access the information from the variable you need to put a ‘$’ in front of it like this:

Try entering those lines into a terminal one at a time; you will see that the first one just gives you another prompt and the second one prints FOO.

But that’s all a bit boring. So let’s make a script to ask the user for some information and then echo that information.

That is more efficient code. However it’s still a bit messy when run. A solution? Good old white spaces!

Now we have an efficient and clean Bash script.

If Statements

An if statement can be used to check for something and do something else depending on the outcome of the check. For example, if I had an ‘apple’, I would want to make sure it’s still an ‘apple’ and not an ‘orange’ because I don’t like Oranges!

The syntax for an if statement is

The else if statement or (elif) is not necessary, but it can be used if needed.

Just to explain this statement,

If statements are an easy concept to grasp as they are similar to the «if» used in spoken English. But say you wanted to have 4 or 5 checks, the answer may be to write 4 or 5 statements but that’s not the most practical way. This is where elif comes in handy.

This saves us from from repetitive scripting. There are better ways to check what the fruit is, but we won’t go into that now.

Storing application stdout to a variable:

Example

This code should output the current users, their respective ttys, and date of login. Note that this strips newlines. Be sure to do any parsing in line ( | grep, etc ) and then pass it to a variable. We will try this again, but grep for tty7, the GUI’s tty.

Example 2

This should output the single user that is currently logged into the WM. Let’s move on to more advanced data manipulation within command substitution.

FUNctions

Bash lets you create a function on the fly, really handy if you plan on using a code block more then once. Functions reduce the amounts of editing you have to do in a script, if and when you have to update your script. Let’s get to it!

Example

Here is an example script:

Although this example is simple, you can see that if you want to change «echo is Called» to say «foo is Called» you would have to edit twice.

Below is the same app using functions.

This example, as you can see may be longer now, but you can imagine how, adding features, this will eliminate code and reduce complexity. Also, you can see if you want to change the echo call, you have to edit one line, not two.

Debugging

This will write each command to standard error (preceded by a ‘+ ’) before it is executed.

Other Scripting Languages related to Bash

tr is one of the most basic applications to pipe data through that uses a basic scripting syntax. In this case, it accepts Regular Expressions. Let’s do a normally complicated task, transforming a string to all uppercase.

Example

The output should look something like this:

Example

the output should look something like this:

AWK ( Short for Aho, Weinberger & Kernighan )

awk has its own custom scripting language, suitable for a tutorial by itself, so I will cover only the basics to help assist when you are bash scripting. This is not meant to be complete or comprehensive in any way.

pidof clone

Let’s make a quick pidof clone that prompts for a process identifier, then echoes the process ID.

Let’s take some pipes out and use only awk for the filtering

is a regular expression match.

There are a lot more commands than the print command, including if statements, etc., and is worth looking into if you are interested in what you see here!

sed is one of the most complicated scripting languages on the GNU / Linux system. I am only going to cover the s/ command here.

Basic Substitution

Try this out to show that sed can not only replace inline, but unlike tr, replace with a longer or shorter string than before.

When this command is run, it should substitute the first appearance of «foo» with «bars».

This is an example of the output.

Beginners/BashScripting (последним исправлял пользователь lnee 2022-02-01 17:36:41)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

How do I execute a bash script in Terminal?

I have a bash script like:

How do I execute this in Terminal?

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

9 Answers 9

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Yet another way to execute it (this time without setting execute permissions):

$prompt: /path/to/script and hit enter. Note you need to make sure the script has execute permissions.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

if in the same directory or

if it’s in the bin folder.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

You could do:
sh scriptname.sh

This is an old thread, but I happened across it and I’m surprised nobody has put up a complete answer yet. So here goes.

The Executing a Command Line Script Tutorial!

Q: How do I execute this in Terminal?

Confusions and Conflicts:

The Path

Extensions

Changing directories

Typing the program name

You will see a listing with owners and permissions. You will notice that you ‘own’ all of the files in this directory. You have full control over this directory and nobody else can easily modify it.

If it does not exist, you can create one:

A: To «execute this script» from the terminal on a Unix/Linux type system, you have to do three things:

1. Tell the system the location of the script. (pick one)

2. Tell the system that the script has permission to execute. (pick one)

There is a great discussion of permissions with a cool chart here.

3. Tell the system the type of script. (pick one)

Bash Beginner Series #1: Create and Run Your First Bash Shell Script

If you have to do it more than once, automate it!

You will often find yourself repeating a single task on Linux over and over again. It may be a simple backup of a directory or it could be cleaning up temporary files or it can even be cloning of a database.

Automating a task is one of the many useful scenarios where you can leverage the power of bash scripting.

Let me show you how to create a simple bash shell script, how to run a bash script and what are the things you must know about shell scripting.

Create and run your first shell script

Let’s first create a new directory named scripts that will host all our bash scripts.

Now inside this ‘scripts directory’, create a new file named hello.sh using the cat command:

Insert the following line in it by typing it in the terminal:

Press Ctrl+D to save the text to the file and come out of the cat command.

You can also use a terminal-based text editor like Vim, Emacs or Nano. If you are using a desktop Linux, you may also use a graphical text editor like Gedit to add the text to this file.

So, basically you are using the echo command to print «Hello World». You can use this command in the terminal directly but in this test, you’ll run this command through a shell script.

Now make the file hello.sh executable by using the chmod command as follows:

And finally, run your first shell script by preceding the hello.sh with your desired shell “bash”:

You’ll see Hello, World! printed on the screen. That was probably the easiest Hello World program you have ever written, right?

Here’s a screenshot of all the steps you saw above:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Convert your shell script into bash script

Confused? Don’t be confused just yet. I’ll explain things to you.

Bash which is short for “Bourne-Again shell” is just one type of many available shells in Linux.

A shell is a command line interpreter that accepts and runs commands. If you have ever run any Linux command before, then you have used the shell. When you open a terminal in Linux, you are already running the default shell of your system.

Bash is often the default shell in most Linux distributions. This is why bash is often synonymous to shell.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

The shell scripts often have almost the same syntaxes, but they also differ sometimes. For example, array index starts at 1 in Zsh instead of 0 in bash. A script written for Zsh shell won’t work the same in bash if it has arrays.

To avoid unpleasant surprises, you should tell the interpreter that your shell script is written for bash shell. How do you do that? You use shebang!

The SheBang line at the beginning of shell script

The line “#!/bin/bash” is referred to as the shebang line and in some literature, it’s referred to as the hashbang line and that’s because it starts with the two characters hash ‘#’ and bang ‘!’.

When you include the line “#!/bin/bash” at the very top of your script, the system knows that you want to use bash as an interpreter for your script. Thus, you can run the hello.sh script directly now without preceding it with bash.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Adding your shell script to the PATH (so that it can be run from any directory)

Bash thought that you were trying to run a command named hello.sh. When you run any command on your terminal; they shell looks for that command in a set of directories that are stored in the PATH variable.

You can use echo to view the contents of that PATH variable:

The colon character (:) separates the path of each of the directories that your shell scans whenever you run a command.

Linux commands like echo, cat etc can be run from anywhere because their executable files are stored in the bin directories. The bin directories are included in the PATH. When you run a command, your system checks the PATH for all the possible places it should look for to find the executable for that command.

If you want to run your bash script from anywhere, as if it were a regular Linux command, add the location of your shell script to the PATH variable.

First, get the location of your script’s directory (assuming you are in the same directory), use the PWD command:

Use the export command to add your scripts directory to the PATH variable.

Notice that I have appended the ‘scripts directory’ to the very end to our PATH variable. So that the custom path is searched after the standard directories.

The moment of truth is here; run hello.sh:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

It works! This takes us to the end of this tutorial. I hope you now have some basic idea about shell scripting. You can download the PDF below and practice what you learned with some sample scripting challenges. Their solutions are also provided in case you need hints.

Shell Scripting for Beginners – How to Write Bash Scripts in Linux

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Shell scripting is an important part of process automation in Linux. Scripting helps you write a sequence of commands in a file and then execute them.

This saves you time because you don’t have to write certain commands again and again. You can perform daily tasks efficiently and even schedule them for automatic execution.

You can also set certain scripts to execute on startup such as showing a particular message on launching a new session or setting certain environment variables.

The applications and uses of scripting are numerous, so let’s dive in.

In this article, you will learn:

The best way to learn is by practicing. I highly encourage you to follow along using Replit. You can access a running Linux shell within minutes.

Introduction to the Bash Shell

The Linux command line is provided by a program called the shell. Over the years, the shell program has evolved to cater to various options.

Different users can be configured to use different shells. But most users prefer to stick with the current default shell. The default shell for many Linux distros is the GNU Bourne-Again Shell (bash). Bash is succeeded by Bourne shell ( sh ).

Bash is very powerful as it can simplify certain operations that are hard to accomplish efficiently with a GUI. Remember that most servers do not have a GUI, and it is best to learn to use the powers of a command line interface (CLI).

What is a Bash Script?

A bash script is a series of commands written in a file. These are read and executed by the bash program. The program executes line by line.

For example, you can navigate to a certain path, create a folder and spawn a process inside it using the command line.

You can do the same sequence of steps by saving the commands in a bash script and running it. You can run the script any number of times.

How Do You Identify a Bash Script?

Scripts start with a bash bang.

Below is an example of the shebang statement.

The path of the bash program can vary. We will see later how to identify it.

Execution rights

Scripts have execution rights for the user executing them.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

File colour

Executable scripts appear in a different colour from rest of the files and folders.

In my case, the scripts with execution rights appear as green.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

How to Create Your First Bash Script

Create a file named hello_world.sh

Find the path to your bash shell.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

In my case, the path is /usr/bin/bash and I will include this in the shebang.

Write the command.

We will echo «hello world» to the console.

Our script will look something like this:

Edit the file hello_world.sh using a text editor of your choice and add the above lines in it.

Provide execution rights to your user.

Modify the file permissions and allow execution of the script by using the command below:

Run the script.

You can run the script in the following ways:

Here’s the output:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntuTwo ways to run scripts

The Basic Syntax of Bash Scripting

Just like any other programming language, bash scripting follows a set of rules to create programs understandable by the computer. In this section, we will study the syntax of bash scripting.

How to define variables

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Tux is also the name of the Linux mascot, the penguin.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntuHi, I am Tux.

Arithmetic Expressions

Below are the operators supported by bash for mathematical calculations:

OperatorUsage
+addition
subtraction
*multiplication
/division
**exponentiation
%modulus

Let’s run a few examples.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntuNote the spaces, these are part of the syntax

Numerical expressions can also be calculated and stored in a variable using the syntax below:

Let’s try an example.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Fractions are not correctly calculated using the above methods and truncated.

For decimal calculations, we can use bc command to get the output to a particular number of decimal places. bc (Bash Calculator) is a command line calculator that supports calculation up to a certain number of decimal points.

echo «scale=2;22/7» | bc

Where scale defines the number of decimal places required in the output.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntuGetting output to 2 decimal places

How to read user input

Sometimes you’ll need to gather user input and perform relevant operations.

In bash, we can take user input using the read command.

Example:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Numeric Comparison logical operators

Syntax:

Example:

Let’s compare two numbers and find their relationship:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Conditional Statements (Decision Making)

The structure of conditional statements is as follows:

Syntax:

The below statement translates to: If a is greater than 40 and b is less than 6.

Example: Let’s find the triangle type by reading the lengths of its sides.

Output:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Looping and skipping

For loops allow you to execute statements a specific number of times.

Looping with numbers:

In the example below, the loop will iterate 5 times.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Looping with strings:

We can loop through strings as well.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

While loop

Example:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

Reading files

Suppose we have a file sample_file.txt as shown below:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

We can read the file line by line and print the output on the screen.

Output:

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntuLines with line number printed

How to execute commands with back ticks

If you need to include the output of a complex command in your script, you can write the statement inside back ticks.

Syntax:

To include it in the bash script, we can enclose it in back ticks.

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

How to get arguments for scripts from the command line

It is possible to give arguments to the script on execution.

$@ represents the position of the parameters, starting from one.

Run it like this:

./script arg1 arg2

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntu

How to Automate Scripts by Scheduling via cron Jobs

Cron is a job scheduling utility present in Unix like systems. You can schedule jobs to execute daily, weekly, monthly or in a specific time of the day. Automation in Linux heavily relies on cron jobs.

Below is the syntax to schedule crons:

Here, * represent represents minute(s) hour(s) day(s) month(s) weekday(s), respectively.

Below are some examples of scheduling cron jobs.

SCHEDULESCHEDULED VALUE
5 0 * 8 *At 00:05 in August.
5 4 * * 6At 04:05 on Sunday.
0 22 * * 1-5At 22:00 on every day-of-week from Monday through Friday.

You can learn about cron in detail in this blog post.

How to Check Existing Scripts in a System

Using crontab

How to run sh script ubuntu. Смотреть фото How to run sh script ubuntu. Смотреть картинку How to run sh script ubuntu. Картинка про How to run sh script ubuntu. Фото How to run sh script ubuntuMy scheduled scripts

Using the find command

If you are interested to read about the find command in detail, check my other post.

Wrapping up

In this tutorial we learned the basics of shell scripting. We looked into examples and syntax which can help us write meaningful programs.

What’s your favorite thing you learned from this tutorial? Let me know on Twitter!

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *