Running shell scripts in linux

How do I run .sh scripts?

Whenever I open a .sh file, it opens it in gedit instead of the terminal. I can’t find any option similar to Right ClickOpen WithOther Application.Terminal. How do I open this file in the terminal?

You shouldn’t use extensions on scripts. At some point in the future, you may find that a different language is more suitable to do the task your current script is doing. And then you have a problem. Do you keep the old name, with a completely misleading extension, or do you rename it, possibly having to edit alot of places where your script is used?

You don’t need the file extension. It’s nice to have but is not needed. The OS doesn’t look at the file extension. It looks at the data

16 Answers 16

Give execute permission to your script:

chmod +x /path/to/yourscript.sh 

Since . refers to the current directory: if yourscript.sh is in the current directory, you can simplify this to:

Actually, you can use . /path/to/yourscript.sh if the script have to set up some environment variables.

Nobody mentions the traditional: ./path/to/yourscript.sh (without the space after . )? I find that one is the simplest and easiest to use. But anyways, here is my alternative that should do almost the same as ./ would, though I don’t see why you wouldn’t use ./ : (FILENAME=~/rem4space.sh;SLL=$(cat $FILENAME|head -1|sed ‘s:^#!\(.*\):\1:g’);[ ! -z $SLL ] && exec $SLL $FILENAME;sh $FILENAME) . edit FILENAME to your liking. Also note that sh will be used if there is no alternative.

You need to mark shell scripts as executable to run them from the file manager:

  1. Right click on your .sh file and select Properties: enter image description here
  2. In the Permissions tab, check Allow executing file as program: enter image description here
  3. Close the Properties window and double-click the file. A dialog will pop up giving you the option to run the script in a terminal: enter image description here

This isn’t working in Ubuntu 13.04. Keeps opening in gedit anyway, never asks me to execute. Edit: Nvm, imjustmatthew answers this.

Before using this we need to make the file permission for execute using chmod. chmod +x filename.sh or chmod 755 filename.sh

Источник

How to Run a Shell Script in Linux [Essentials Explained for Beginners]

Here are all the essential details you should know about executing a shell script in the Linux command line.

Читайте также:  Namespace in linux kernel

That maybe simple, but it doesn’t explain a lot. Don’t worry, I’ll do the necessary explaining with examples so that you understand why a particular syntax is used in the given format while running a shell script. I am going to use this one line shell script to make things as uncomplicated as possible:

[email protected]:~/Scripts$ cat hello.sh echo "Hello World!"

Method 1: Running a shell script by passing the file as argument to shell

The first method involves passing the script file name as an argument to the shell. Considering that bash is the default shell, you can run a script like this:

Do you know the advantage of this approach? Your script doesn’t need to have the execute permission. Pretty handy for quick and simple tasks. Run A Shell Script LinuxIf you are not familiar already, I advise you to read my detailed guide on file permission in Linux. Keep in mind that it needs to be a shell script that you pass as argument. A shell script is composed of commands. If you use a normal text file, it will complain about incorrect commands. Running Text File As Script in LinuxIn this approach, you explicitly specified that you want to use bash as the interpreter for the script. Shell is just a program and bash is an implementation of that. There are other such shells program like ksh, zsh, etc. If you have other shells installed, you can use that as well instead of bash. For example, I installed zsh and used it to run the same script: Execute Shell Script With Zsh

Method 2: Execute shell script by specifying its path

The other method to run a shell script is by providing its path. But for that to be possible, your file must be executable. Otherwise, you’ll have “permission denied” error when you try to execute the script. So first you need to make sure that your script has the execute permission. You can use the chmod command to give yourself this permission like this:

Once your script is executable, all you need to do is to type the file name along with its absolute or relative path. Most often you are in the same directory so you just use it like this:

Running Shell Script In Other Directory

If you are not in the same directory as your script, you can specify it the absolute or relative path to the script:

That ./ before the script is important (when you are in the same directory as the script)

Executing Shell Scripts Linux

Why can you not use the script name when you are in the same directory? That is because your Linux systems looks for the executables to run in a few selected directories that are specified in the PATH variable. Here’s the value of PATH variable for my system:

[email protected]:~$ echo $PATH /home/abhishek/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
  • /home/abhishek/.local/bin
  • /usr/local/sbin
  • /usr/local/bin
  • /usr/sbin
  • /usr/bin
  • /sbin
  • /bin
  • /usr/games
  • /usr/local/games
  • /snap/bin

The binaries or executable files for Linux commands like ls, cat etc are located in one of those directories. This is why you are able to run these commands from anywhere on your system just by using their names. See, the ls command is located in /usr/bin directory.

Читайте также:  Linux cat all but first line

Locating Command Linux

When you specify the script WITHOUT the absolute or relative path, it cannot find it in the directories mentioned in the PATH variable.

Why most shell scripts contain #! /bin/bash at the beginning of the shell scripts?

Remember how I mentioned that shell is just a program and there are different implementations of shells.

When you use the #! /bin/bash, you are specifying that the script is to run with bash as interpreter. If you don’t do that and run a script in ./script.sh manner, it is usually run with whatever shell you are running.

Does it matter? It could. See, most of the shell syntax is common in all kind of shell but some might differ.

For example, the array behavior is different in bash and zsh shells. In zsh, the array index starts at 1 instead of 0.

Bash Vs Zsh

Using #! /bin/bash indicates that the script is bash shell script and should be run with bash as interpreter irrespective of the shell which is being used on the system. If you are using zsh specific syntax, you can indicate that it is zsh script by adding #! /bin/zsh as the first line of the script.

The space between #! /bin/bash doesn’t matter. You can also use #!/bin/bash.

Was it helpful?

I hope this article added to your Linux knowledge. If you still have questions or suggestions, please leave a comment.

Expert users can still nitpick this article about things I missed out. But the problem with such beginner topics is that it is not easy to find the right balance of information and avoid having too much or too few details.

If you are interested in learning bash script, we have an entire Bash Beginner Series on our sysadmin focused website Linux Handbook.

If you want, you may also purchase the ebook with additional exercises to support Linux Handbook.

Источник

Запуск скрипта sh в Linux

Вся сила Linux в использовании терминала. Это такая командная оболочка, где вы можете выполнять различные команды, которые будут быстро и эффективно выполнять различные действия. Ну впрочем, вы наверное это уже знаете. Для Linux было создано множество скриптов, которые выполняются в различных командных оболочках. Это очень удобно, вы просто объединяете несколько команд, которые выполняют определенное действие, а затем выполняете их одной командой или даже с помощью ярлыка.

Но у новичков может возникнуть вопрос — как запустить скрипт в Linux, что для этого нужно сделать, что будет происходить и какие команды нужно выполнить. Но сначала нужно рассмотреть как работают скрипты и что такое исполняемость.

Как работают скрипты

В Linux почти не используется расширение файла для опережения его типа на системном уровне. Это могут делать файловые менеджеры и то не всегда. Вместо этого, используются сигнатуры начала файла и специальные флаги. Система считает исполняемыми только те файлы, которым присвоен атрибут исполняемости.

Читайте также:  Linux shell in browser

Теперь о том, как работают скрипты. Это обычные файлы, которые содержат текст. Но если для них установлен атрибут исполняемости, то для их открытия используется специальная программа — интерпретатор, например, оболочка bash. А уже интерпретатор читает последовательно строку за строкой и выполняет все команды, которые содержатся в файле. У нас есть несколько способов выполнить запуск скрипта linux. Мы можем запустить его как любую другую программу через терминал или же запустить оболочку и сообщить ей какой файл нужно выполнять. В этом случае не нужно даже флага исполняемости.

Запуск скрипта sh в Linux

Сначала рассмотрим пример небольшого sh скрипта:

Вторая строка — это действие, которое выполняет скрипт, но нас больше всего интересует первая — это оболочка, с помощью которого его нужно выполнить. Это может быть не только /bin/bash, но и /bin/sh, и даже /usr/bin/python или /usr/bin/php. Также часто встречается ситуация, что путь к исполняемому файлу оболочки получают с помощью утилиты env: /usr/bin/env php и так далее. Чтобы выполнить скрипт в указанной оболочке, нужно установить для него флаг исполняемости:

Мы разрешаем выполнять запуск sh linux всем категориям пользователей — владельцу, группе файла и остальным. Следующий важный момент — это то место где находится скрипт, если вы просто наберете script.sh, то поиск будет выполнен только глобально, в каталогах, которые записаны в переменную PATH и даже если вы находитесь сейчас в той папке где находится скрипт, то он не будет найден. К нему нужно указывать полный путь, например, для той же текущей папки. Запуск скрипта sh в linux:

Если вы не хотите писать полный путь к скрипту, это можно сделать, достаточно переместить скрипт в одну из папок, которые указаны в переменной PATH. Одна из них, которая предназначена для ручной установки программ — /usr/local/bin.

cp script.sh /usr/local/bin/script.sh

Теперь вы можете выполнить:

Это был первый способ вызвать скрипт, но есть еще один — мы можем запустить оболочку и сразу же передать ей скрипт, который нужно выполнить. Вы могли редко видеть такой способ с bash, но он довольно часто используется для скриптов php или python. Запустим так наш скрипт:

А если нам нужно запустить скрипт на php, то выполните:

Вот так все просто здесь работает. Так можно запустить скрипт как фоновый процесс, используйте символ &:

Даже запустить процесс linux не так сложно.

Выводы

Как видите, запуск скрипта sh в linux — это довольно простая задача, даже если вы еще плохо знакомы с терминалом. Существует действительно много скриптов и некоторые из них вам возможно придется выполнять. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector