Run install script linux

Установка или запуск программ формата sh и run в Linux

Многообразие вариантов установки программного обеспечения на дистрибутивы Линукс не ограничиваются только пакетными базами (RPM, DEB), портативными форматами приложений (Snap, Flatpak, Appimage) или исходным кодом.

Иногда пользователю могут попадаться такие форматы установочных файлов, как sh или run. Помню, что когда сам впервые столкнулся с ними, то не мог понять, как их запустить. Потому специально для таких же «непонимашек», каким был я, написан этот пост, в котором расскажу и покажу что это за форматы и как с ними работать.

Что представляют из себя файлы sh и run файлы?

Оба формата установочных файлов являются скриптами, то есть содержат некую последовательность команд, которые при выполнении производят необходимые действия с дистрибутивом — устанавливают нужные зависимости, создают необходимые папки и файлы, задают необходимые для работы ПО права. Раз эти файлы являются скриптами, то вполне возможно просмотреть их содержимое при помощи текстового редактора (графического или консольного). Обратите внимание на скриншот, представленный ниже.

Для поста я скачал установочный файл run для установки драйверов Nvidia и программу Mediaget, про которую уже рассказывал в предыдущей заметке на канале.

Если теперь открыть содержимое файла с установкой драйверов Nvidia в текстовом редакторе (в примере использую консольный редактор Neovim), то мы увидим те самые команды, про которые говорил ранее.

Если перейти в папку mediaget, то увидим внутри три sh-файла. Если откроем их в редакторе, то также увидим набор команд, которые выполняются при запуске.

Обратите внимание на самую первую строку в обоих примера.

Она уже упоминалась в заметке про автоматизацию удаления файлов при помощи bash-скрипта. В этой статье я как раз таки объяснил, что указание этой строки в начале файла превращает его в понятный для консоли скрипт.

Запуск sh и run файлов

Настоятельно рекомендую перед тем как запускать скачанные где-либо sh и run-файлы просмотреть их содержимое в текстовом редакторе. Если какие-то команды покажутся вам подозрительными или странными, то лучше найти информацию о том, что они делают в интернете, чтобы запуском сомнительного скрипта не позволить вредоносному коду попасть на компьютер. Но давайте исходить из того, что вы все уже проверили и сомнений в нормальности файлов нет. Как установить программы при помощи этих файлов?

Помним, что любой файл в Linux можно прочитать (read), изменить (write) и запустить (executable). Об этом я рассказывал в статье о правах на файлы и папки.

Нас, как вы понимаете интересует запуск. Для этого нужно сделать скрипт исполняемым. Происходит это при помощи следующей команды:

Если вы используете нестандартную bash-оболочку, то после выполнения команды скрипты, готовые к запуску будут подсвечены другим цветом.

Читайте также:  Linux mysql client gui

Обратите внимание на пример выше — в папке mediaget все скрипты уже являются исполняемыми и потому выделены зеленым цветом, а вот файл для установки драйверов Nvidia другого цвета. После ввода команды все sh и run файлы становятся зелеными.

Теперь файл готов к запуску, осуществить который мы можем указав на это оболочке:

Так как драйвера Nvidia у меня уже установлены, а программа Mediaget в этой папке работает только для DEB-платформ, то запускать скрипты не стану, но в статьях, на которые давал ссылки ранее есть момент запуска и демонстрация его успешности.

Отдельно встает вопрос об использовании команды sudo, дающей текущему пользователю права суперпользователя. Я поступаю очень просто: сначала запускаю скрипт без sudo, а если оболочка ругается на то, что скрипту для выполнения определенных процедур не хватает прав, уже использую «власть» суперпользователя. Поэтому важно, повторюсь, просматривать скрипты перед их запуском, так как команда запущенная от суперпользователя может сотворить с системой все, что угодно.

Подведем итог

Мы узнали, что sh и run установочные файлы представляют собой последовательность программ, которые выполняются для установки ПО на дистрибутив, познакомились с правилами безопасности при работе с этими файлами и научились их запускать. Видите сколько полезной и нужной информации выхватили из такого небольшого поста!

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

Источник

snovakovic / ubuntu_software_installer

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#! /bin/bash
# run it as sudo yes | sh ubuntu_software_installer.sh
# CURL
sudo apt-get install curl
# CHROME
wget -q -O — https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add —
sudo sh -c ‘ echo «deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main» >> /etc/apt/sources.list.d/google-chrome.list ‘
# VS CODE
curl https://packages.microsoft.com/keys/microsoft.asc | gpg —dearmor > microsoft.gpg
sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
sudo sh -c ‘ echo «deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main» > /etc/apt/sources.list.d/vscode.list ‘
# SKYPE (preview)
curl https://repo.skype.com/data/SKYPE-GPG-KEY | sudo apt-key add —
echo » deb [arch=amd64] https://repo.skype.com/deb unstable main » | sudo tee /etc/apt/sources.list.d/skype-unstable.list
# KODI
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:team-xbmc/ppa
# # INSTALL
sudo apt-get update
sudo apt-get install kodi google-chrome-stable code terminator git skypeforlinux
# CLIPIT
sudo apt-get install clipit
# NVM
curl https://raw.githubusercontent.com/creationix/nvm/v0.33.4/install.sh | bash
# NODE
nvm install stable
# # GIT config
git config —global user.email » stefan.novakovich@gmail.com «
git config —global user.name » snovakovic «
# AVN
npm install -g avn avn-nvm avn-n
avn setup
echo Finished Installing Programs !

Источник

How to Run an INSTALL.sh Script on Linux in 4 Easy Steps

This article was co-authored by wikiHow staff writer, Nicole Levine, MFA. Nicole Levine is a Technology Writer and Editor for wikiHow. She has more than 20 years of experience creating technical documentation and leading support teams at major web hosting and software companies. Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions.

Читайте также:  Manjaro linux package manager

The wikiHow Tech Team also followed the article’s instructions and verified that they work.

This article has been viewed 457,413 times.

Did you download Linux software that came with an install.sh file? Install.sh is a simple text-based shell script that makes it easy to install software. To use an install.sh script, you’ll first need to make it executable using chmod +x install.sh. Then, you can execute the script in a terminal with the command ./install.sh or sudo ./install.sh. This wikiHow guide will walk you through executing an install.sh file from the Linux command line using Ubuntu, Debian, and any other version of Linux.

  • To make install.sh file executable, use the command chmod +x install.sh.
  • To execute the script, run the command ./install.sh.
  • Depending on permissions, you may need to start each command with sudo to gain superuser (root) access.

Image titled Execute INSTALL.sh Files in Linux Using Terminal Step 4

  • Before installing software, make sure to check the README or INSTALL file that came in your download for specific instructions and installation options.

Image titled Execute INSTALL.sh Files in Linux Using Terminal Step 5

  • If the file you downloaded is compressed into a TGZ or TAR.GZ archive, be sure to unpack the files first.
  • You can extract a TGZ or TAR.GZ file using the command tar -xzvf filename.tgz .
  • To make sure you’re in the right directory, type ls -a and press Enter. You should see your install.sh file, as well as all other files in the directory.

Image titled Execute INSTALL.sh Files in Linux Using Terminal Step 6

  • If you’re unable to change the permissions, you’ll need root access. Instead, run sudo chmod +x install.sh and press Enter.
  • If you don’t see an error, you’ll know the install script is now executable.

Image titled Execute INSTALL.sh Files in Linux Using Terminal Step 4

  • You can also use the command sudo bash install.sh or sudo sh install.sh to run the script.
  • If you’re just installing the software in your own home directory and don’t need root permissions, you can use omit sudo and use ./install.sh instead.
  • Depending on the script and app you’re installing, you may be prompted to complete additional steps to install the software.

Community Q&A

Enter these commands into the terminal: cd /location of file/. For example, /home/username/Documents./name_of_file.extension. Replace these with the name of the file/program and the extension (commonly .desktop in Linux or .exe (executable) or .sh (script). Make sure the file/program is marked as executable in its properties.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

Читайте также:  Где лежат исполняемые файлы linux

I typed: chmod +x install.sh but the output is chmod: cannot access ‘install.sh’: No such file or directory.

This means that there is no install.sh file. Linux is case-sensitive, so if you type the file name as install.sh, it won’t find a file that is named, for example, INSTALL.sh. Also check for typos, like typing isntall.sh instead of install.sh. Try typing ls to list all files in the current directory. If the install.sh file is not in the current directory, you need to change into the directory with that file using the cd command.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

I want my (.sh) files to be executable by 1 word like «test» without commanding «./test.sh | bash test.sh». How to do that?

If that’s a program that someone else wrote, you can usually run «sudo make install» to install it, and then it will be possible to just type the program name. If it is a script that you wrote yourself, do the following: Add the line «#!/bin/bash» (without the quotation marks) to the beginning of the script file. Rename the file to not have «.sh» at the end, for example «test.sh» to just «test». Finally, move your file to the «/usr/bin» directory. Then, you can just type the word (in this example, «test») to execute the script. Also, when working from the Linux bash shell, you don’t need to type the » | bash test.sh» part, you can just write «./test.sh».

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

Источник

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