Add script to path linux

Add a bash script to path

I want to add a small script to the linux PATH so I don’t have to actually run it where it’s physically placed on disk. The script is quite simple is about giving apt-get access through a proxy I made it like this:

#!/bin/bash array=( $@ ) len=$ _args=$ sudo http_proxy="http://user:password@server:port" apt-get $_args 

Then I saved this as apt-proxy.sh, set it to +x (chmod) and everything is working fine when I am in the directory where this file is placed. My question is : how to add this apt-proxy to PATH so I can actually call it as if it where the real apt-get ? [from anywhere] Looking for command line only solutions, if you know how to do by GUI its nice, but not what I am looking for.

Depending on your needs/options, either pointing PATH to the script (already detailed in answers) or moving the script to a location already available will both achieve the desired result. I usually drop a script in /usr/local/bin .

5 Answers 5

  • Save the script as apt-proxy (without the .sh extension) in some directory, like ~/bin .
  • Add ~/bin to your PATH , typing export PATH=$PATH:~/bin
  • If you need it permanently, add that last line in your ~/.bashrc . If you’re using zsh , then add it to ~/.zshrc instead.
  • Then you can just run apt-proxy with your arguments and it will run anywhere.

Note that if you export the PATH variable in a specific window it won’t update in other bash instances.

You don’t need to export PATH as it is (very likely) already marked as exported. Also, it might be better to prepend your personal paths, rather than to append them to existing PATH .

@compguy24: so that they are searched before. If you have an executable my_command in both dirA and in dirB , and your PATH is PATH=dirA:dirB then the one in dirA will be found first, and hence it’s dirA/my_command that will be run. Usually, the personal ones are meant to override the system-wide ones; that’s why it’s usually preferable to prepend your personal ones to PATH .

You want to define that directory to the path variable, not the actual binary e.g.

where MYDIR is defined as the directory containing your binary e.g.

You should put this in your startup script e.g. .bashrc such that it runs each time a shell process is invoked.

Note that order is important, and the PATH is evaluated such that if a script matching your name is found in an earlier entry in the path variable, then that’s the one you’ll execute. So you could name your script as apt-get and put it earlier in the path. I wouldn’t do that since it’s confusing. You may want to investigate shell aliases instead.

Читайте также:  Learn command line linux

I note also that you say it works fine from your current directory. If by that you mean you have the current directory in your path ( . ) then that’s a potential security risk. Someone could put some trojan variant of a common utility (e.g. ls ) in a directory, then get you to cd to that directory and run it inadvertently.

Источник

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

Take the first step towards shell scripting. Learn what it takes to create a simple bash script and how to run it.

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:

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.

Читайте также:  Format usb from linux to windows

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.

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

You may have noticed that I used ./hello.sh to run the script; you will get an error if you omit the leading ./

[email protected]:~/scripts$ hello.sh hello.sh: command not found

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:

echo $PATH /home/user/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

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.

export PATH=$PATH:/home/user/scripts

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:

[email protected]:~/scripts$ hello.sh Hello, World!

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.

Since I introduced you to PATH variable, stay tuned for the next bash scripting tutorial where I discuss shell variables in detail.

Читайте также:  Vmware start vmware tools linux

Источник

Переменная PATH в Linux

Когда вы запускаете программу из терминала или скрипта, то обычно пишете только имя файла программы. Однако, ОС Linux спроектирована так, что исполняемые и связанные с ними файлы программ распределяются по различным специализированным каталогам. Например, библиотеки устанавливаются в /lib или /usr/lib, конфигурационные файлы в /etc, а исполняемые файлы в /sbin/, /usr/bin или /bin.

Таких местоположений несколько. Откуда операционная система знает где искать требуемую программу или её компонент? Всё просто — для этого используется переменная PATH. Эта переменная позволяет существенно сократить длину набираемых команд в терминале или в скрипте, освобождая от необходимости каждый раз указывать полные пути к требуемым файлам. В этой статье мы разберёмся зачем нужна переменная PATH Linux, а также как добавить к её значению имена своих пользовательских каталогов.

Переменная PATH в Linux

Для того, чтобы посмотреть содержимое переменной PATH в Linux, выполните в терминале команду:

На экране появится перечень папок, разделённых двоеточием. Алгоритм поиска пути к требуемой программе при её запуске довольно прост. Сначала ОС ищет исполняемый файл с заданным именем в текущей папке. Если находит, запускает на выполнение, если нет, проверяет каталоги, перечисленные в переменной PATH, в установленном там порядке. Таким образом, добавив свои папки к содержимому этой переменной, вы добавляете новые места размещения исполняемых и связанных с ними файлов.

Для того, чтобы добавить новый путь к переменной PATH, можно воспользоваться командой export. Например, давайте добавим к значению переменной PATH папку/opt/local/bin. Для того, чтобы не перезаписать имеющееся значение переменной PATH новым, нужно именно добавить (дописать) это новое значение к уже имеющемуся, не забыв о разделителе-двоеточии:

Теперь мы можем убедиться, что в переменной PATH содержится также и имя этой, добавленной нами, папки:

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

В ОС Ubuntu значение переменной PATH содержится в файле /etc/environment, в некоторых других дистрибутивах её также можно найти и в файле /etc/profile. Вы можете открыть файл /etc/environment и вручную дописать туда нужное значение:

Можно поступить и иначе. Содержимое файла .bashrc выполняется при каждом запуске оболочки Bash. Если добавить в конец файла команду export, то для каждой загружаемой оболочки будет автоматически выполняться добавление имени требуемой папки в переменную PATH, но только для текущего пользователя:

Выводы

В этой статье мы рассмотрели вопрос о том, зачем нужна переменная окружения PATH в Linux и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.

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

Источник

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