Меню Рубрики

Linux script execute script

How do I execute a bash script in Terminal?

I have a bash script like:

How do I execute this in Terminal?

9 Answers 9

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

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

cd to the directory that contains the script, or put it in a bin folder that is in your $PATH

if in the same directory or

if it’s in the bin folder.

You could do:
sh scriptname.sh

Firstly you have to make it executable using: chmod +x name_of_your_file_script .

After you made it executable, you can run it using ./same_name_of_your_file_script

Change your directory to where script is located by using cd command

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:

  • You do not need an ‘extension’ (like .sh or .py or anything else), but it helps to keep track of things. It won’t hurt. If the script name contains an extension, however, you must use it.
  • You do not need to be in any certain directory at all for any reason.
  • You do not need to type out the name of the program that runs the file (BASH or Python or whatever) unless you want to. It won’t hurt.
  • You do not need sudo to do any of this. This command is reserved for running commands as another user or a ‘root’ (administrator) user. Great post here.

(A person who is just learning how to execute scripts should not be using this command unless there is a real need, like installing a new program. A good place to put your scripts is in your

/bin folder. You can get there by typing cd

/bin or cd $HOME/bin from the terminal prompt. You will have full permissions in that folder.)

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

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

  • Type the full path with the script name (e.g. /path/to/script.sh ). You can verify the full path by typing pwd or echo $PWD in the terminal.
  • Execute from the same directory and use ./ for the path (e.g. ./script.sh ). Easy.
  • Place the script in a directory that is on the system PATH and just type the name (e.g. script.sh ). You can verify the system PATH by typing echo $PATH or echo -e $ if you want a neater list.

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

  • Set the «execute bit» by typing chmod +x /path/to/script.sh in the terminal.
  • You can also use chmod 755 /path/to/script.sh if you prefer numbers. There is a great discussion with a cool chart here.

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

Источник

How to execute script in the current shell on Linux?

Is there a way to mark a script to be executed in the current shell from whitin It? I know I can use:

but I need a way to include the «dot» way inside the script.

Edit: Here is the case. I have a script «myscript.sh» located in directory A:

When the script is executed in normal a way:

When exiting the script I cannot list the directory. When script is started in the current shell:

There is no problem. I need a way to include this «dot» way inside my script so It can be called without It.

5 Answers 5

There are two ways of executing a script in the shell. Depending upon your needs, you will have to do one of the following (don’t do both!).

  1. Launch the script as a program, where it has its own process.
  2. Source the script as a bunch of text, where the text is processed by the current shell.

To launch the script as a program:

  • Add the line #!/bin/bash as the first line of the script

This will be read by the loader, which has special logic that interperts the first two characters #! as «launch the program coming next, and pass the contents into it». Note this only properly works for programs written to receive the contents

To source the script into the current shell:

  • type the command . script.sh or source script.sh

Note: . in bash is equivalent to source in bash.

This acts as if you typed in the contents of «script.sh». For example, if you set a variable in «script.sh» then that variable will be set in the current shell. You will need to undefine the variable to clear it from the current shell.

This differs heavily from the #!/bin/bash example, because setting a variable in the new bash subprocess won’t impact the shell you launched the subprocess from.

Источник

How to execute a shell script from C in Linux?

How can I execute a shell script from C in Linux?

6 Answers 6

It depends on what you want to do with the script (or any other program you want to run).

If you just want to run the script system is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).

If you want to either feed the shell script via its standard input or consume its standard output you can use popen (and pclose ) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.

Both of these are library functions that do a lot under the hood, but if they don’t meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.

The system calls of interest are fork , execve , and waitpid . You may want to use one of the library wrappers around execve (type man 3 exec for a list of them). You may also want to use one of the other wait functions ( man 2 wait has them all). Additionally you may be interested in the system calls clone and vfork which are related to fork.

fork duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process’s process id (or an error) returned.

execve replaces the current program with a new program (keeping the same process id).

waitpid is used by a parent process to wait on a particular child process to finish.

Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won’t need, changing the session, or changing the environmental variables.

You may also be interested in the pipe and dup2 system calls. pipe creates a pipe (with both an input and an output file descriptor). dup2 duplicates a file descriptor as a specific file descriptor ( dup is similar but duplicates a file descriptor to the lowest available file descriptor).

Источник

Create and execute a shell script in Linux home directory

I would like to create (and execute) a shell script in my home directory (/home/user).

Have tried the following:

where am I going wrong?

(am trying to set up a shortcut to navigate to a different directory)

3 Answers 3

If you want to execute the script in the current shell (as opposed to in a subshell), use the source (or . ) command:

This should then change the directory as expected.

In addition, sourcing also allows you to set and change environment variables in the current shell—a very frequent question in its own right 🙂

What is exactly wrong here? That you are still in /home/user after the script executes? Well thats because executing the script creates a child shell that returns to the parent shell once the script ends. Therefore your cd has NO EFFECT in your current shell.

That won’t work because of what the other answer says. The script operates in a child shell.

For a shortcut like that, you could set up an alias, edit the .bashrc file in your home directory and add a line like

alias shortcut=’cd /mypath’

Substitute «shortcut» for whatever you want to name it, and mypath to the path you want. Restart the shell (close terminal and reopen or w/e) and that should work just as you want. Then you can use «shortcut» anywhere you want in the shell.

Источник

Как запустить Bash скрипт в Linux

Как системный администратор, вполне вероятно, что вы написали несколько сценариев Bash для автоматизации вашей работы. Например, вы можете запускать сценарии Bash для резервного копирования вашей работы или для регистрации некоторых событий, происходящих на вашем сервере.

Скрипты Bash, как и скрипты, написанные на других языках программирования, могут запускаться различными способами.

В этой статье мы расскажем о всех способах запуска скрипта Bash в Linux.

Подготовка

Прежде чем вы сможете запустить ваш скрипт, вам нужно, чтобы ваш скрипт был исполняемым. Чтобы сделать исполняемый скрипт в Linux, используйте команду chmod и присвойте файлу права execute. Вы можете использовать двоичную или символическую запись, чтобы сделать ее исполняемой.

$ chmod u+x script
$ chmod 744 script

Если вы не являетесь владельцем файла, вам необходимо убедиться, что вы принадлежите к правильной группе или что права доступа предоставлены «другой» группе в вашей системе.

В некоторых дистрибутивах ваш файл будет выделен другим цветом, когда он исполняемый.

Теперь, когда ваш файл исполняемый, давайте посмотрим, как можно легко запустить скрипт Bash.

Запустить Bash скрипт из пути к скрипту

Чтобы запустить Bash скрипт в Linux, просто укажите полный путь к скрипту и укажите аргументы, которые могут потребоваться для запуска Bash скрипта.

В качестве примера, скажем, у вас есть Bash-скрипт, расположенный в вашем домашнем каталоге.

Чтобы выполнить этот скрипт, вы можете указать полный путь к скрипту, который вы хотите запустить.

# Абсолютный путь
$ /home/user/script

# Абсолютный путь с аргументами
$ /home/user/script «john» «jack» «jim»

Кроме того, вы можете указать относительный путь к скрипту Bash, который вы хотите запустить.

# Относительный путь
$ ./script

# Относительный путь с аргументами
$ ./script «john» «jack» «jim»

Таким образом вы узнали, как легко запустить Bash-скрипт в своей системе.

Запустить Bash скрипт, используя bash

Чтобы запустить скрипт Bash в вашей системе, вы должны использовать команду bash и указать имя скрипта, который вы хотите выполнить, с необязательными аргументами.

Кроме того, вы можете использовать sh, если в вашем дистрибутиве установлена утилита sh.

В качестве примера, скажем, вы хотите запустить скрипт Bash с именем script. Чтобы выполнить его с помощью утилиты bash, вы должны выполнить следующую команду

This is the output from your script!

Выполнить скрипт Bash, используя sh, zsh, dash

В зависимости от вашего дистрибутива, в вашей системе могут быть установлены другие утилиты оболочки.

Bash — интерпретатор оболочки, установленный по умолчанию, но вы можете захотеть выполнить ваш скрипт с использованием других интерпретаторов. Чтобы проверить, установлен ли интерпретатор оболочки в вашей системе, используйте команду which и укажите нужный интерпретатор.

Когда вы определили интерпретатор оболочки, который хотите использовать, просто вызовите его, чтобы легко запустить скрипт.

Запуск скрипта Bash из любого места

В некоторых случаях вы можете запускать скрипты Bash, где бы вы ни находились в вашей системе.

Чтобы запустить скрипт Bash из любой точки вашей системы, вам нужно добавить свой скрипт в переменную среды PATH.

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

This is the output from script!

Кроме того, вы можете изменить переменную среды PATH в вашем файле .bashrc и использовать команду source для обновления вашей текущей среды Bash.

Выйдите из файла и используйте команду source для файла bashrc для внесения изменений.

Отлично! Теперь ваш скрипт может быть запущен из любой точки вашей системы.

Запуск Bash скриптов из графического интерфейса

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

Чтобы запустить ваши скрипты с использованием GNOME, вы должны установить в проводнике Ask what to do для исполняемых файлов.

Закройте это окно и дважды щелкните файл скрипта, который вы хотите выполнить.

При двойном щелчке вам предлагаются различные варианты: вы можете выбрать запуск скрипта (в терминале или нет) или просто отобразить содержимое файла.

В этом случае мы заинтересованы в запуске этого скрипта в терминале, поэтому нажмите на эту опцию.

Успех! Ваш скрипт был успешно выполнен

Заключение

Из этого руководства вы узнали, как легко запускать Bash скрипты в своей системе, указав путь к скрипту или интерпретаторы, доступные на вашем хосте. Вы узнали, что можете сделать это еще проще, добавив путь к скрипту в переменную среды PATH или используя существующие функции в пользовательском интерфейсе GNOME.

Источник

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

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

  • Skype for business для mac os
  • Skin pack for windows 7 mac os
  • Skin changer mac os
  • Sketch crack mac os
  • Skachat mac os sierra