Как создать bash файл в windows

С появлением оболочки Bash Windows 10 вы можете теперь создавать и запускать сценарии оболочки Bash в Windows 10. Вы также можете включить команды Bash в командный файл Windows или сценарий PowerShell.

С появлением оболочки Bash Windows 10 вы можете теперь создавать и запускать сценарии оболочки Bash в Windows 10. Вы также можете включить команды Bash в командный файл Windows или сценарий PowerShell.

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

Как написать сценарий Bash в Windows 10

При написании сценариев оболочки в Windows помните, что Windows и UNIX-подобные системы, такие как Linux, используют разные символы «конца строки» в текстовых файлах в сценариях оболочки.

Другими словами, это означает, что вы не можете просто написать сценарий оболочки в «Блокноте». Сохраните файл в «Блокноте», и он не будет правильно интерпретироваться Bash. Тем не менее, вы можете использовать более сложные текстовые редакторы, например, Notepad ++ позволяет вам предоставить файл конечных символов UNIX, нажав «Редактировать»> «Преобразование EOL»> «Формат UNIX / OSX».

Однако вам лучше просто написать сценарий оболочки в самой среде Bash. В среде Bash, основанной на Ubuntu, есть как редакторы vi, так и nano. Редактор vi более мощный, но если вы никогда не использовали его раньше, вы можете начать с nano. Это проще в использовании, если вы новичок.

Например, чтобы создать скрипт bash в nano, вы выполните следующую команду в bash:

nano ~/myscript.sh

Это откроет текстовый редактор Nano, указанный в файле с именем «myscript.sh» в домашнем каталоге вашей учетной записи пользователя. (Символ «~» представляет ваш домашний каталог, поэтому полный путь: /home/username/myscript.sh.)

Запустите сценарий оболочки с помощью строки:

#!/bin/bash

Введите команды, которые вы хотите запустить, каждый из которых находится в отдельной строке. Скрипт будет запускать каждую команду по очереди. Добавьте символ «#» перед строкой, чтобы рассматривать его как «комментарий», что поможет вам и другим людям понять сценарий, но который не запускается как команда. Для получения более совершенных трюков обратитесь к более подробному руководству по сценариям Bash в Linux. Те же методы будут работать в Bash на Ubuntu в Windows.

Обратите внимание: нет возможности запуска программ Windows из среды Bash. Вы ограничены командами и утилитами терминала Linux, так же, как и в обычной Linux-системе.

Например, давайте просто воспользуемся базовым сценарием «hello world» в качестве примера:

#!/bin/bash # set the STRING variable STRING='Hello World!' # print the contents of the variable on screen echo $STRING

Если вы используете текстовый редактор Nano, вы можете сохранить файл, нажав Ctrl + O, а затем Enter. Закройте редактор, нажав Ctrl + X.

Сделайте исполняемый файл сценария, а затем запустите его

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

chmod +x ~/myscript.sh

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

~/myscript.sh

(Если скрипт находится в текущем каталоге, вы можете запустить его с ./myscript.sh)

Как работать с файлами Windows в сценарии Bash

Чтобы получить доступ к файлам Windows в сценарии, вам нужно указать их путь в / mnt / c, а не в пути к ним. Например, если вы хотите указать файл C: Users Bob Downloads test.txt, вам нужно указать путь /mnt/c/Users/Bob/Downloads/test.txt. Для получения дополнительной информации обратитесь к нашему руководству по расположению файлов в оболочке Bash Windows 10.

Как включить команды Bash в скрипт Batch или PowerShell

Наконец, если у вас есть существующий командный файл или сценарий PowerShell, в который вы хотите включить команды, вы можете запускать команды Bash напрямую, используя bash -c команда.

Например, чтобы запустить команду Linux в окне командной строки или PowerShell, вы можете запустить следующую команду:

bash -c 'command'

Этот трюк позволяет добавлять команды Bash в командные файлы или сценарии PowerShell. Окно оболочки Bash появится, когда запущена команда Bash.

Обновить: Если у вас установлено несколько Linux-сред, вы можете использовать команду wslconfig для выбора среды Linux по умолчанию, используемой при запуске bash -c команда.


Чтобы создать ярлык для сценария Bash изнутри Windows, просто создайте ярлык, как обычно. Для цели ярлыка используйте bash -c которую мы описали выше, и укажем на созданный вами сценарий Bash.

Например, вы укажете ярлык на » bash -c '~/myscript.sh' Msgstr «запустить приведенный выше пример скрипта. Вы также можете просто запустить эту команду из окна командной строки или окна PowerShell.

  • Как написать сценарий Bash в Windows 10
  • Сделайте исполняемый файл сценария, а затем запустите его
  • Как работать с файлами Windows в сценарии Bash
  • Как включить команды Bash в скрипт Batch или PowerShell
  • Tweet

    Share

    Link

    Plus

    Send

    Send

    Pin

    Написание скриптов в Windows 10 Bash

    Справка:https://www.howtoip.com/how-to-create-and-run-bash-shell-scripts-on-windows-10/
    Пример тестировался мной в подсистеме linux windows pro build 15063

    Как писать скрипты на win 10 bash

    Вы можете писать сценарии в системе Windows, но вам нужно выполнить преобразование EOL> формат UNIX / OSX, чтобы дать символ строки UNIX конца файла
    (Это можно сделать в некоторых программных блокнотах, таких как блокнот ++)

    В среде Bash на основе Ubuntu с двумяVIс участиемНано-нано

    НаноИспользуйте: nano ~ / myscript.sh — командный файл (файл использует абсолютный путь в bash)
    ~ — Представляет ваш домашний каталог, поэтому полный путь — /home/username/myscript.sh)

    Описание скрипта: добавить#!/bin/bash

    Весь процесс скрипта от написания до исполнения

    Случай:

    #!/bin/bash
    read -p “Please input yes or no:” anw
    case $anw in
    [yY][eE][sS]|[yY])
       echo yes
       ;;
    [nN][oO]|[nN])
       echo no
       ;;
    *)
       echo false
       ;;
    esac

    Оцените ввод да или нет

    1. Выполните подсистему windows 10 linux: напрямую введите bash.exe в командную строку или запустите и нажмите Enter.
    2. Запустите редактор файлов: nano yesorno-new.sh
    3. После ввода содержимого нажмите ctrl + o, а затем Enter, чтобы сохранить. Снова нажмите Ctrl + X
    4. Сделайте скрипт исполняемым и запустите его: Измените права доступа: chmod + x ~ / yesorno.sh Выполните: ~ / yesorno.sh
      График эффекта бега:

      wKioL1nEf0DQHwvMAABOuuLKtrE582.png-wh_50

    Как использовать файлы Windows в сценарии Bash

    Чтобы получить доступ к файлам Windows в скрипте, вам необходимо указать их путь в / mnt / c, а не путь к ним.
    Например
    Путь в Windows: C: users bob downloads test.txt
    Путь в Bash: /mnt/c/users/bob/downloadstest.txt

    Как включить команды Bash в пакетные сценарии или сценарии PowerShell

    Запустите команды Linux из PowerShell:
    bash -c «команда»
    wKioL1nEf0GBJRIiAAAIVfWCG-k991.png-wh_50

    Основы bash-скриптов

    Что это такое?

    Bash-скрипты — это сценарии командной строки, написанные для оболочки bash.
    Сценарии командной строки позволяют исполнять те же команды, которые можно ввести
    в интерактивном режиме.
    Интерактивный режим — оболочка читает команды, вводимые пользователем. Пользователь имеет возможность
    взаимодействия с оболочкой.

    Создание скриптов

    Для того, чтобы создать bash-скрипт, необходимо создать файл с расширением *.sh
    Первой строкой необходимо указать, что этот файл является исполняемым командной оболочкой bash:
    #!/bin/bash

    Исполнение скриптов

    Существует 2 основных способа вызвать bash-скрипт:

    1. bash *.sh
    2. ./*sh

    Для того, чтобы воспользоваться вторым способом, необходимо сначала выдать файлу правильные права:
    sudo chmod +x *.sh

    Работа с переменными внутри скриптов

    Создание простой переменной со значением (обязательно без пробелов):
    myVariable="test"

    Вернуть в переменную значение команды bash:

    или

    Использование переменной в тексте:
    echo "$myOs"

    Использование переменной с командами:
    echo $myOs

    Пример простой работы с переменными:

    num1=50
    num2=45
    sum=$((num1+num2))
    echo "$num1 + $num2 = $sum"

    Параметры скриптов

    Параметры скриптов — значения, переданные в файл при его вызове, например:
    echo text — вызов команды echo с параметром text.

    Внутри bash-скриптов можно обращаться к специальным переменным:
    $0 — хранит в себе название файла.
    $ + любая цифра — переданный файлу параметр.

    Пример использования:
    bash *.sh hello

    *.sh:
    echo $1

    Результат:
    hello

    Условные операторы

    if-then

    user=someUsername
    if grep $user /etc/passwd
    then
    echo "The user $user Exists"
    fi

    if-then-else

    user=someUsername
    if grep $user /etc/passwd
    then
    echo "The user $user Exists"
    else
    echo "The user $user doesn’t exist"
    fi

    elif

    user=someUsername
    if grep $user /etc/passwd
    then
    echo "The user $user Exists"
    elif ls /home
    then
    echo "The user doesn’t exist but anyway there is a directory under /home"
    fi

    Перенос строки в bash

    С помозью слеша можно переносить продолжение команды на новую строку:

    yaourt -S 
    package1 
    packege2 
    package3

    Циклы в bash-скриптах

    for

    Самый простой вариант цикла:

    for var in "the first" second "the third"
    do
    echo "This is: $var"
    done

    Цикл из результата работы команды:

    file="myfile"
    for var in $(cat $file)
    do
    echo " $var"
    done

    Цикл из результата работы команды с разделителем полей:

    file="/etc/passwd"
    IFS=$'n'
    for var in $(cat $file)
    do
    echo " $var"
    done

    IFS (Internal Field Separator) — специальная переменная окружения, которая позволяет указывать разделители полей.
    По умолчанию bash считает разделителями следующие символы: пробел, знак табуляции, знак перевода строки.

    for в стиле C

    for (( i=1; i <= 10; i++ ))
    do
    echo "number is $i"
    done

    while

    var1=5
    while [ $var1 -gt 0 ]
    do
    echo $var1
    var1=$[ $var1 - 1 ]
    done

    Обработка вывода в цикле

    for (( a = 1; a < 10; a++ ))
    do
    echo "Number is $a"
    done > myfile.txt
    echo "finished."

    С помощью символа «>» можно куда-нибудь перенаправить вывод, например в файл.
    В данном примере оболочка создаст файл myFile.txt и перенаправит в него вывод.

    Запуск bash-скриптов вместе с системой

    Раньше было принято размещать все скрипты, которые запускаются по умолчанию в файле /etc/rc.local.
    Этот файл все еще существует, но это пережиток системы инициализации SysVinit и теперь он сохраняется только для совместимости.
    Скрипты же нужно загружать только с помощью Systemd.

    Для этого достаточно создать простой юнит-файл и добавить его в автозагрузку, как любой другой сервис.
    Сначала создадим этот файл:
    sudo vi /lib/systemd/system/runscript.service
    Добавим содержимое:
    [Unit]
    Description=My Script Service
    After=multi-user.target

    [Service]
    Type=idle
    ExecStart=/usr/bin/local/script.sh

    [Install]
    WantedBy=multi-user.target

    В секции Unit мы даем краткое описание нашему файлу и говорим с помощью опции After,
    что нужно запускать этот скрипт в многопользовательском режиме (multi-user).

    Секция Service самая важная, здесь мы указываем тип сервиса — idle, это значит, что нужно просто запустить и забыть,
    вести наблюдение нет необходимости, а затем в параметре ExecStart указываем полный путь к нашему скрипту.

    Осталось выставить правильные права:
    sudo chmod 644 /lib/systemd/system/runscript.service

    Затем обновить конфигурацию и добавить в автозагрузку Linux новый скрипт:

    sudo systemctl daemon-reload
    sudo systemctl enable myscript.service

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

    sudo chmod u+x /usr/local/bin/script
    В параметрах мы передаем утилите адрес файла скрипта. Исполняемость — это обязательный параметр для всех способов.

    Up To This Point . . .

    This is the third part in a series focused on getting familiar with Git for Windows developers. The series assumes little or no experience using the command line. If you missed the first few posts, here is what we have covered so far:

    • Installing and configuring Git on your Windows machine
    • Navigating directories (folders) from the Bash command line
    • Examined a reference containing commonly-used (but basic) Git and Bash commands

    In the previous post, we learned how to navigate directories within the Windows file system, create new directories, and delete directories. Now let’s look at creating files, and performing rudimentary (VERY rudimentary) text editing from the Bash command prompt.

    Before We Proceed . . .

    Let’s create a directory to use for the following examples. Open your Bash Command Line Interface (CLI) and make sure you are in your default Windows user folder. Create a new directory within your user folder called BashExcercises, and then move into that directory (Review the previous post if you are unsure how to do this):

    Create a Directory for the Following Exercises

    Create-BashExcercises-Directory

    Also remember, when we are explaining syntax, we will often use square brackets to denote optional items, and angle brackets to denote use-provided content. In the following:

    mkdir [options] <FileName>

    We do not type the square brackets or angle brackets. The [options] are, well, optional, meaning there may be none or there may be many, and the <Filename> is required and provided by the user.

    Bash: Create/Edit Files (touch/echo)

    There are a couple of ways to create a new file using the Bash command prompt. The most basic is the touch command. The purpose of the touch command is ostensibly to change/modify the date/time stamps of files. However, it is commonly used to create new files as well, since, when used without any optional arguments, it does just that: creates a new file, with a date stamp.

    Using the Touch Command to Create a New Text File

    The syntax for the touch command is

    Create a new file with a date stamp:
    touch [options] <filename> 

    There are a number of options for use with the touch command, but for now, we are going to focus on simple file creation, and we won’t be using any of the options. If we want to create a simple text file, we can type:

    Create a new Text File Named MyNewTextFile:
    $ touch MyNewTextFile.txt 

    Type the above into your Bash window and hit enter:

    Bash-Create-New-Text-File

    Remember from the previous post that in many cases, when a Bash command executes successfully, we are rewarded with simply a new command prompt. However, we can use the ls command we learned from the last post to examine the contents of our directory:

    Bash-Show-New-Text-File-In-Direcotry

    What do you know? There it is. Now, you could open the new file using Notepad (or the text editor of your choosing), but you won’t see much. We have created an empty text file. To open the file using Notepad from the Bash prompt, simply type:

    Open MyNewTextFile.txt in Notepad using Bash:
    $ notepad MyNewTextFile.txt

    Or, of course, you could open the file the old-fashioned way — by double clicking on it with your mouse!

    Using the echo Command to Write Strings as Output

    Before we look at using echo to create a new file, we should understand a little about what echo DOES.

    The primary design purpose of echo is apparently to write strings to the standard output (usually, the Bash CLI).

    The syntax for echo is:

    Echo Command Syntax:
    $ echo [options] <string>

    Let’s try that now. Type the following into Bash:

    Output a line of Text to the Bash Screen:
    $ echo show this line on the screen

    Bash-Echo-Command-Write-Text-To-Screen

    We can also tell the echo command to write a line of text to a file, using the following syntax:

    Syntax: Append text to the end of a file:
    $ echo [options] <Text string> >> <FileName>

    By using the >> (double right-hand angle-brackets) operator, we tell Bash to append the text to the end of the file. Type the following into the Bash window and hit enter:

    $ echo This line was added to the end of the file >> MyNewTextFile.txt

    Bash-Append-Line-To-Text-File

    Now, if we use our $ notepad MyNewTextFile.txt command, we see the following:

    Open-Text-File-After-Append-Line

    Close that window, and let’s add another line. Type the following and hit enter:

    Adding Another Line of Text:
    $ echo This is another line of text >> MyNewTextFile.txt

    Then use $ notepad MyNewTextFile.txt again:

    Open-Text-File-After-Another Append-Line

    Huh. Looks like it worked, kind of. Apparently, Bash isn’t kidding about appending the new text to the end of the file. Happily, we can use the > (a single right-hand angle bracket) operator to replace the text in the current file and get rid of that mess. Type this and hit enter. Then open the file in Notepad again:

    Replace the Text in a File with a New Text String:
    $ echo This line replaced the old mess > MyNewTextFile.txt

    Your Bash window should look like THIS:

    Bash-Replace_Line-In-Text-File

    And you should see this in your Notepad window:

    Open-Text-File-After-Replace-Line

    Use the Echo Command to Create a New File with Text Content:

    Ok, back to the original subject — creating a new text file. We can use echo to create a new file, and include the specified text string as content. In fact, it works the same as when we appended or replaced the text in an existing file, because, lacking an option argument telling it not to, Bash will assume that if the file specified in our echo command does not exist, that we want to create one. Type the following and hit enter:

    $ echo This is a new line in a new file >> DifferentTextFile.txt

    Then use ls -1 to display the directory contents. This is what your Bash window should look like:

    Bash-Create-New-Text-File-With-Echo-Command

    Note the presence of our new file. Let’s open it in Notepad, and see what there is to see:

    DifferentTextFile - Notepad

    Well, well well. Whadd’ya know!

    Bash: Remove Files (rm)

    Ok, now let’s get rid of our first file. To remove (delete) files using Bash, we use the rm command. The syntax for removing files is as follows:

    rm [options] <FileName>

    SO now, let’s delete that first file, MyNewTextFile.txt. Type the following, hit enter, then use the ls -1 command to display the directory contents:

    rm MyNewTextFile.txt 

    Your Bash window should look like this:

    Bash-Remove-Text-File

    Remove a Directory and all Contents (rm -rf)

    In the previous post, we discussed how to remove an empty directory. But what if we want to remove a direcory and all of its contents? We use the rm command with the -r and -f options:

    Syntax for Removing a Directory and All of its Contents:

    rm -rf <FolderName>

    So now we are going to remove the BashExcercises directory we created at the beginning of this post. Of course, we can’t remove a directory if we are currently IN that directory. So first, let’s return to the directory above (in this case, our home folder) using the cd .. Comand (the cd Command, followed by a single space, followed by two periods in a row. This one means “move up one level”).

    Next, type the following into your Bash window, hit enter, and then use the ls -d */ command to view the directories within the current directory (which should be, at this point, your Windows User folder):

    $ rm -rf BashExcercises

    When you are done, your Bash window should resemble this (note that the directories are organized alphabetically in columns, and the BashExcercises directory is no longer there. Also note that for obvious reasons, your user folder will contain different folders than mine!).

    Bash-Remove-Directory-List-Directory-Contents

    Now, let’s use everything we just learned in this post, plus we’ll add one final tidbit at the end which you may find useful. We’re going to step through this right quick. We will:

    1. Add one more new directory
    2. Add a file containing a line of text to the new directory
    3. Remove the directory and its contents
    4. Have Bash tell us what was removed
    1. Add a New Directory Named OneLastFolder to our current directory:
    $ mkdir OneLastFolder
    2. Add a New File Named OneLastFile.txt, containing the text “One more text line” to the new folder:
    $ echo One more text line >> OneLastFolder/OneMoreFile.txt

    Notice in the above, I did not navigate into the new folder to create the new file, but simply used the relative path from my current location.

    3. Remove the directory and all its contents, and have Bash tell us what was done:
    rm -rfv OneLastFolder

    Notice in the above, I added one more optional argument, the -v option (for “verbose”). This tells Bash to print the actions it took to the output window.

    When you have done all of that, your window should look like this:

    Bash-Add-Folder-File-Remove-All

    There you have it. You now have the most basic set of tools for using the Bash Command Line Interface. From here, we are ready to examine the basic command line operations required to start using Git to manage our code. We’ll pick that up in the next post in this series.

    Additional Resources

    • Part I in this series — Set up and configure Git on your Windows Machine
    • Part II in this series — Basic file system navigation using Bash
    • Basic Git and Bash Command Line Reference
    • An A-Z Index of the Bash command line for Linux
    • Git Reference
    • The Pro Git Book by Scott Chacon (eBook)
    • Pro Git (Expert’s Voice in Software Development)Image 15
    • Git Cheat Sheet
    • Github
    • Help on Github

    Image 16

    CodeProject

    My name is John Atten, and my username on many of my online accounts is xivSolutions. I am Fascinated by all things technology and software development. I work mostly with C#, Javascript/Node.js, Various flavors of databases, and anything else I find interesting. I am always looking for new information, and value your feedback (especially where I got something wrong!)

    Up To This Point . . .

    This is the third part in a series focused on getting familiar with Git for Windows developers. The series assumes little or no experience using the command line. If you missed the first few posts, here is what we have covered so far:

    • Installing and configuring Git on your Windows machine
    • Navigating directories (folders) from the Bash command line
    • Examined a reference containing commonly-used (but basic) Git and Bash commands

    In the previous post, we learned how to navigate directories within the Windows file system, create new directories, and delete directories. Now let’s look at creating files, and performing rudimentary (VERY rudimentary) text editing from the Bash command prompt.

    Before We Proceed . . .

    Let’s create a directory to use for the following examples. Open your Bash Command Line Interface (CLI) and make sure you are in your default Windows user folder. Create a new directory within your user folder called BashExcercises, and then move into that directory (Review the previous post if you are unsure how to do this):

    Create a Directory for the Following Exercises

    Create-BashExcercises-Directory

    Also remember, when we are explaining syntax, we will often use square brackets to denote optional items, and angle brackets to denote use-provided content. In the following:

    mkdir [options] <FileName>

    We do not type the square brackets or angle brackets. The [options] are, well, optional, meaning there may be none or there may be many, and the <Filename> is required and provided by the user.

    Bash: Create/Edit Files (touch/echo)

    There are a couple of ways to create a new file using the Bash command prompt. The most basic is the touch command. The purpose of the touch command is ostensibly to change/modify the date/time stamps of files. However, it is commonly used to create new files as well, since, when used without any optional arguments, it does just that: creates a new file, with a date stamp.

    Using the Touch Command to Create a New Text File

    The syntax for the touch command is

    Create a new file with a date stamp:
    touch [options] <filename> 

    There are a number of options for use with the touch command, but for now, we are going to focus on simple file creation, and we won’t be using any of the options. If we want to create a simple text file, we can type:

    Create a new Text File Named MyNewTextFile:
    $ touch MyNewTextFile.txt 

    Type the above into your Bash window and hit enter:

    Bash-Create-New-Text-File

    Remember from the previous post that in many cases, when a Bash command executes successfully, we are rewarded with simply a new command prompt. However, we can use the ls command we learned from the last post to examine the contents of our directory:

    Bash-Show-New-Text-File-In-Direcotry

    What do you know? There it is. Now, you could open the new file using Notepad (or the text editor of your choosing), but you won’t see much. We have created an empty text file. To open the file using Notepad from the Bash prompt, simply type:

    Open MyNewTextFile.txt in Notepad using Bash:
    $ notepad MyNewTextFile.txt

    Or, of course, you could open the file the old-fashioned way — by double clicking on it with your mouse!

    Using the echo Command to Write Strings as Output

    Before we look at using echo to create a new file, we should understand a little about what echo DOES.

    The primary design purpose of echo is apparently to write strings to the standard output (usually, the Bash CLI).

    The syntax for echo is:

    Echo Command Syntax:
    $ echo [options] <string>

    Let’s try that now. Type the following into Bash:

    Output a line of Text to the Bash Screen:
    $ echo show this line on the screen

    Bash-Echo-Command-Write-Text-To-Screen

    We can also tell the echo command to write a line of text to a file, using the following syntax:

    Syntax: Append text to the end of a file:
    $ echo [options] <Text string> >> <FileName>

    By using the >> (double right-hand angle-brackets) operator, we tell Bash to append the text to the end of the file. Type the following into the Bash window and hit enter:

    $ echo This line was added to the end of the file >> MyNewTextFile.txt

    Bash-Append-Line-To-Text-File

    Now, if we use our $ notepad MyNewTextFile.txt command, we see the following:

    Open-Text-File-After-Append-Line

    Close that window, and let’s add another line. Type the following and hit enter:

    Adding Another Line of Text:
    $ echo This is another line of text >> MyNewTextFile.txt

    Then use $ notepad MyNewTextFile.txt again:

    Open-Text-File-After-Another Append-Line

    Huh. Looks like it worked, kind of. Apparently, Bash isn’t kidding about appending the new text to the end of the file. Happily, we can use the > (a single right-hand angle bracket) operator to replace the text in the current file and get rid of that mess. Type this and hit enter. Then open the file in Notepad again:

    Replace the Text in a File with a New Text String:
    $ echo This line replaced the old mess > MyNewTextFile.txt

    Your Bash window should look like THIS:

    Bash-Replace_Line-In-Text-File

    And you should see this in your Notepad window:

    Open-Text-File-After-Replace-Line

    Use the Echo Command to Create a New File with Text Content:

    Ok, back to the original subject — creating a new text file. We can use echo to create a new file, and include the specified text string as content. In fact, it works the same as when we appended or replaced the text in an existing file, because, lacking an option argument telling it not to, Bash will assume that if the file specified in our echo command does not exist, that we want to create one. Type the following and hit enter:

    $ echo This is a new line in a new file >> DifferentTextFile.txt

    Then use ls -1 to display the directory contents. This is what your Bash window should look like:

    Bash-Create-New-Text-File-With-Echo-Command

    Note the presence of our new file. Let’s open it in Notepad, and see what there is to see:

    DifferentTextFile - Notepad

    Well, well well. Whadd’ya know!

    Bash: Remove Files (rm)

    Ok, now let’s get rid of our first file. To remove (delete) files using Bash, we use the rm command. The syntax for removing files is as follows:

    rm [options] <FileName>

    SO now, let’s delete that first file, MyNewTextFile.txt. Type the following, hit enter, then use the ls -1 command to display the directory contents:

    rm MyNewTextFile.txt 

    Your Bash window should look like this:

    Bash-Remove-Text-File

    Remove a Directory and all Contents (rm -rf)

    In the previous post, we discussed how to remove an empty directory. But what if we want to remove a direcory and all of its contents? We use the rm command with the -r and -f options:

    Syntax for Removing a Directory and All of its Contents:

    rm -rf <FolderName>

    So now we are going to remove the BashExcercises directory we created at the beginning of this post. Of course, we can’t remove a directory if we are currently IN that directory. So first, let’s return to the directory above (in this case, our home folder) using the cd .. Comand (the cd Command, followed by a single space, followed by two periods in a row. This one means “move up one level”).

    Next, type the following into your Bash window, hit enter, and then use the ls -d */ command to view the directories within the current directory (which should be, at this point, your Windows User folder):

    $ rm -rf BashExcercises

    When you are done, your Bash window should resemble this (note that the directories are organized alphabetically in columns, and the BashExcercises directory is no longer there. Also note that for obvious reasons, your user folder will contain different folders than mine!).

    Bash-Remove-Directory-List-Directory-Contents

    Now, let’s use everything we just learned in this post, plus we’ll add one final tidbit at the end which you may find useful. We’re going to step through this right quick. We will:

    1. Add one more new directory
    2. Add a file containing a line of text to the new directory
    3. Remove the directory and its contents
    4. Have Bash tell us what was removed
    1. Add a New Directory Named OneLastFolder to our current directory:
    $ mkdir OneLastFolder
    2. Add a New File Named OneLastFile.txt, containing the text “One more text line” to the new folder:
    $ echo One more text line >> OneLastFolder/OneMoreFile.txt

    Notice in the above, I did not navigate into the new folder to create the new file, but simply used the relative path from my current location.

    3. Remove the directory and all its contents, and have Bash tell us what was done:
    rm -rfv OneLastFolder

    Notice in the above, I added one more optional argument, the -v option (for “verbose”). This tells Bash to print the actions it took to the output window.

    When you have done all of that, your window should look like this:

    Bash-Add-Folder-File-Remove-All

    There you have it. You now have the most basic set of tools for using the Bash Command Line Interface. From here, we are ready to examine the basic command line operations required to start using Git to manage our code. We’ll pick that up in the next post in this series.

    Additional Resources

    • Part I in this series — Set up and configure Git on your Windows Machine
    • Part II in this series — Basic file system navigation using Bash
    • Basic Git and Bash Command Line Reference
    • An A-Z Index of the Bash command line for Linux
    • Git Reference
    • The Pro Git Book by Scott Chacon (eBook)
    • Pro Git (Expert’s Voice in Software Development)Image 15
    • Git Cheat Sheet
    • Github
    • Help on Github

    Image 16

    CodeProject

    My name is John Atten, and my username on many of my online accounts is xivSolutions. I am Fascinated by all things technology and software development. I work mostly with C#, Javascript/Node.js, Various flavors of databases, and anything else I find interesting. I am always looking for new information, and value your feedback (especially where I got something wrong!)

    Bash (Bourne Again Shell) — это командная строка и графический пользовательский интерфейс, распространяемый со всеми дистрибутивами Linux. Использование Bash в Windows 10 было непростым процессом. Однако Windows 11 включает в себя обновленную подсистему Windows для Linux (WSL 2.0), которая позволяет устанавливать и использовать Bash проще, чем когда-либо.

    Новая версия WSL запускает настоящее ядро ​​Linux внутри виртуальной машины. Это означает, что любой дистрибутив Linux, который вы запускаете под WSL, включает Bash.

    Как установить WSL и Bash в Windows 11

    Чтобы установить и запустить операционные системы Linux, включающие Bash, в вашей системе Windows 11, вам необходимо сначала установить WSL. В Windows 11 это простой процесс с использованием Windows Terminal. Не запускайте CMD (командную строку) — Windows Terminal — это другое приложение.

    1. Нажмите кнопку «Пуск» и введите «терминал» в поле поиска. В панели терминала Windows выберите «Запуск от имени администратора».

    Примечание. Если Windows Terminal не запускается, возможно, вам потребуется обновить его. Посетите Microsoft Store и установите последнюю версию Windows Terminal.

    2. Введите следующую команду: wsl –install в командной строке и нажмите Enter. Эта единственная команда загрузит и установит последнюю версию подсистемы Windows для Linux. Загрузка составляет несколько сотен мегабайт, поэтому процесс установки может занять некоторое время.

    3. По завершении вы должны увидеть сообщение: «Запрошенная операция выполнена успешно». Когда вы увидите это сообщение, перезагрузите систему, чтобы завершить установку WSL. Вы можете ввести shutdown / r / t 0 в терминале Windows, чтобы начать перезагрузку.

    4. После перезагрузки системы процесс продолжится установкой Ubuntu в качестве дистрибутива Linux по умолчанию. Вам будет предложено ввести имя пользователя и пароль для системы Linux.

    5. Когда вы закончите, Ubuntu автоматически запустится в оболочке Bash. Вы можете использовать те же команды, которые обычно используете в Linux, включая установку приложений Linux в эту виртуальную среду.

    6. Вы можете установить другие дистрибутивы Linux, если хотите. Чтобы узнать, какие из них доступны для установки, снова откройте Windows Terminal (Powershell), введите wsl –list –online и нажмите Enter. Вы увидите такие варианты, как Opensuse, Debian и другие.

    7. Вы можете установить любой из этих дистрибутивов, набрав wsl –install -d <<distr name>> в терминале Windows. Повторится тот же процесс, что и при предыдущей установке Ubuntu, и вам потребуется ввести имя пользователя и пароль для завершения установки.

    Примечание. Вы также можете установить любой дистрибутив Linux в Windows из Магазина Microsoft.

    Как запустить дистрибутив Linux и использовать Bash

    Есть два метода, которые вы можете использовать для запуска вашего дистрибутива Linux. Если вы установили Ubuntu, вы можете выбрать меню «Пуск», ввести Ubuntu и выбрать приложение Ubuntu для его запуска.

    Кроме того, вы можете запустить терминал Windows и просто ввести команду Ubuntu, чтобы запустить оболочку Linux Bash в среде Ubuntu.

    Чтобы просмотреть список всех доступных команд Linux, которые вы можете использовать в Bash, введите help -d

    Вы можете получить более подробную информацию об отдельных командах, набрав help и имя команды. Например, help printf возвращает сведения о команде и информацию о каждом параметре команды.

    Некоторые из наиболее распространенных команд Bash, которые большинство людей используют при первом запуске, включают:

    • Интерактивный режим: ввод команд в интерфейс командной строки (терминал Windows).
    • Пакетный режим: запустите текстовый файл, содержащий все команды, которые вы хотите, чтобы Linux выполнял по порядку. Многие люди создают эти сценарии, используя синтаксис программирования.

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

    Чтобы запустить сценарий в Bash, просто создайте текстовый файл в своем любимом файловом редакторе, таком как Блокнот, и сохраните его в удобном для вас месте.

    Уникальность сценария Bash заключается в том, что первая строка должна быть «#!». за которым следует путь вашего пути Linux bash. Чтобы увидеть, что это такое, запустите Ubuntu и введите bash в окно командной строки. Это обеспечит путь Bash.

    Создайте новый текстовый файл и включите эту первую строку вверху. В случае с этим примером это будет:

    #! /user/bin/bash

    Следуйте этой строке с каждой последовательной командой, которую вы хотите запустить в Linux. В этом примере:

    • Строка 1: использует команду echo для отображения текста пользователю на экране.
    • Строка 2: объединяет эхо с командой даты, чтобы вернуть сегодняшнюю дату.
    • Строка 3: объединяет эхо с командой whoami, чтобы вернуть ваше имя пользователя.

    Сохраните этот текстовый файл с расширением .sh. Запомните путь к этому файлу.

    Затем откройте терминал Windows и используйте команду cd, чтобы перейти к пути, по которому вы сохранили сценарий Bash.

    Чтобы запустить скрипт, введите bash <<script name>>.

    Это очень простой пример, но он демонстрирует, как вы можете использовать такой файл для создания целых программ сценариев Bash. Даже операторы программирования, такие как операторы IF, доступны для включения возможностей принятия решений в ваш сценарий.

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


    Версии

    Версия Дата выхода
    0,99 1989-06-08
    1,01 1989-06-23
    2,0 1996-12-31
    2,02 1998-04-20
    2,03 1999-02-19
    2,04 2001-03-21
    2.05b 2002-07-17
    3.0 2004-08-03
    3,1 2005-12-08
    3,2 2006-10-11
    4,0 2009-02-20
    4,1 2009-12-31
    4,2 2011-02-13
    4,3 2014-02-26
    4,4 2016-09-15

    Привет, мир, используя переменные

    Создайте новый файл hello.sh со следующим содержимым и дайте ему исполняемые разрешения с помощью chmod +x hello.sh .

    Выполнить / ./hello.sh через: ./hello.sh

    #!/usr/bin/env bash
    
    # Note that spaces cannot be used around the `=` assignment operator
    whom_variable="World"
    
    # Use printf to safely output the data
    printf "Hello, %sn" "$whom_variable"
    #> Hello, World
    

    Это приведет к печати Hello, World до стандартного вывода при его выполнении.

    Чтобы сообщить bash, где сценарий вам нужен, нужно указать его в содержащую директорию, обычно с ./ если это ваш рабочий каталог, где . является псевдонимом текущего каталога. Если вы не укажете каталог, bash попытается найти скрипт в одном из каталогов, содержащихся в $PATH среды $PATH .


    Следующий код принимает аргумент $1 , который является первым аргументом командной строки, и выводит его в отформатированной строке, следующей за Hello, .

    Выполнение / выполнение через: ./hello.sh World

    #!/usr/bin/env bash
    printf "Hello, %sn" "$1"
    #> Hello, World
    

    Важно отметить, что $1 должен быть указан в двойной кавычки, а не одинарной кавычки. "$1" по желанию расшифровывается до первого аргумента командной строки, а '$1' вычисляется до литеральной строки $1 .

    Примечание по безопасности:
    Прочтите последствия для безопасности, забывая процитировать переменную в оболочках bash, чтобы понять важность размещения текста переменной в двойных кавычках.

    Привет, мир

    Интерактивная оболочка

    Оболочка Bash обычно используется в интерактивном режиме: она позволяет вводить и редактировать команды, а затем выполняет их при нажатии клавиши Return . Многие Unix-подобные и Unix-подобные операционные системы используют Bash в качестве своей оболочки по умолчанию (особенно Linux и macOS). Терминал автоматически запускает интерактивный процесс оболочки Bash при запуске.

    Выведите Hello World , введя следующее:

    echo "Hello World"
    #> Hello World  # Output Example
    

    Заметки

    • Вы можете изменить оболочку, просто набрав имя оболочки в терминале. Например: sh , bash и т. Д.

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


    Неинтерактивная оболочка

    Оболочка Bash также может быть запущена неинтерактивно из сценария, в результате чего оболочка не требует взаимодействия с человеком. Интерактивное поведение и сценарий поведения должны быть одинаковыми — важное рассмотрение дизайна оболочки Unix V7 Bourne и транзитно Bash. Поэтому все, что можно сделать в командной строке, можно поместить в файл сценария для повторного использования.

    Выполните следующие шаги, чтобы создать сценарий Hello World :

    1. Создайте новый файл hello-world.sh

      touch hello-world.sh
      
    2. Сделайте исполняемый файл скрипта, запустив chmod +x hello-world.sh

    3. Добавьте этот код:

      #!/bin/bash
      echo "Hello World"
      

      Строка 1 : первая строка скрипта должна начинаться с символьной последовательности #! , называемый shebang 1 . Shebang поручает операционной системе запустить /bin/bash , оболочку Bash, передав ей путь сценария в качестве аргумента.

      Eg /bin/bash hello-world.sh

      Строка 2 : используется команда echo для записи Hello World на стандартный вывод.

    1. Выполните скрипт hello-world.sh из командной строки, используя одно из следующих:

      • ./hello-world.sh — наиболее часто используемые и рекомендуемые
      • /bin/bash hello-world.sh
      • bash hello-world.sh — предполагая, что /bin находится в вашей $PATH
      • sh hello-world.sh

    Для реального использования в производстве вы бы .sh расширение .sh (что вводит в заблуждение в любом случае, поскольку это скрипт Bash, а не сценарий sh ) и, возможно, переместите файл в каталог в вашей PATH чтобы он был доступен вам независимо от того, ваш текущий рабочий каталог, как и системная команда, например cat или ls .

    К числу распространенных ошибок относятся:

    1. Забыв применить к файлу разрешение на выполнение, то есть chmod +x hello-world.sh , в результате ./hello-world.sh: Permission denied выход ./hello-world.sh: Permission denied .

    2. Редактирование сценария в Windows, который создает неправильные символы окончания строки, которые Bash не может обрабатывать.

      Общим симптомом является : command not found где возврат каретки заставил курсор к началу строки, переписав текст перед двоеточием в сообщении об ошибке.

      Сценарий можно исправить с dos2unix программы dos2unix .

      Пример использования: dos2unix hello-world.sh

      dos2unix редактирует файл inline.

    3. Используя sh ./hello-world.sh , не понимая, что bash и sh представляют собой отдельные оболочки с различными функциями (хотя, поскольку Bash совместим с обратной связью, противоположная ошибка безвредна).

      Во всяком случае, просто полагаясь на строку shebang скрипта, гораздо предпочтительнее явно писать bash или sh (или python или perl или awk или ruby или …) перед именем файла каждого скрипта.

      Обычная строка shebang, используемая для того, чтобы сделать ваш скрипт более переносимым, заключается в использовании #!/usr/bin/env bash вместо жесткого кодирования пути к Bash. Таким образом, /usr/bin/env должен существовать, но помимо этого, bash просто должен быть на вашем PATH . На многих системах /bin/bash не существует, и вы должны использовать /usr/local/bin/bash или какой-либо другой абсолютный путь; это изменение позволяет избежать необходимости выяснять детали этого.


    1 Также упоминается как sha-bang, hashbang, pound-bang, hash-pling.

    help <command>
    

    Это отобразит страницу справки Bash (ручная) для указанного встроенного устройства.

    Например, help unset покажет:

    unset: unset [-f] [-v] [-n] [name ...]
       Unset values and attributes of shell variables and functions.
    
       For each NAME, remove the corresponding variable or function.
    
       Options:
         -f    treat each NAME as a shell function
         -v    treat each NAME as a shell variable
         -n    treat each NAME as a name reference and unset the variable itself
           rather than the variable it references
    
       Without options, unset first tries to unset a variable, and if that fails,
       tries to unset a function.
    
       Some variables cannot be unset; also see `readonly'.
    
       Exit Status:
       Returns success unless an invalid option is given or a NAME is read-only.
    

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

    help -d
    

    Hello World с пользовательским вводом

    Следующее предложит пользователю ввести, а затем сохранит этот ввод в виде строки (текста) в переменной. Затем переменная используется для предоставления пользователю сообщения.

    #!/usr/bin/env bash
    echo  "Who are you?"
    read name
    echo "Hello, $name."
    

    Команда read здесь читает одну строки данных из стандартного ввода в переменное name . Затем это делается с помощью $name и печатается по стандарту, используя echo .

    Пример вывода:

    $ ./hello_world.sh
    Who are you?
    Matt
    Hello, Matt.
    

    Здесь пользователь ввел имя «Мэтт», и этот код использовался, чтобы сказать « Hello, Matt. ,

    И если вы хотите добавить что-то к значению переменной во время его печати, используйте фигурные скобки вокруг имени переменной, как показано в следующем примере:

    #!/usr/bin/env bash
    echo  "What are you doing?"
    read action
    echo "You are ${action}ing."
    

    Пример вывода:

    $ ./hello_world.sh
    What are you doing?
    Sleep
    You are Sleeping.
    

    Здесь, когда пользователь вводит действие, во время печати к этому действию добавляется «ing».

    Обработка именованных аргументов

    #!/bin/bash
    
    deploy=false
    uglify=false
    
    while (( $# > 1 )); do case $1 in
       --deploy) deploy="$2";;
       --uglify) uglify="$2";;
       *) break;
     esac; shift 2
    done
    
    $deploy && echo "will deploy... deploy = $deploy"
    $uglify && echo "will uglify... uglify = $uglify"
    
    # how to run
    # chmod +x script.sh
    # ./script.sh --deploy true --uglify false
    

    Hello World в режиме «Отладка»

    $ cat hello.sh 
    #!/bin/bash 
    echo "Hello World"
    $ bash -x hello.sh 
    + echo Hello World
    Hello World
    

    Аргумент -x позволяет вам пройти через каждую строку в скрипте. Один хороший пример:

    $ cat hello.sh
    #!/bin/bash 
    echo "Hello Worldn" 
    adding_string_to_number="s"
    v=$(expr 5 + $adding_string_to_number) 
    
    $ ./hello.sh 
    Hello World
    
    expr: non-integer argument
    

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

    $ bash -x hello.sh 
    + echo Hello Worldn
    Hello World
    
    + adding_string_to_number=s
    + expr 5 + s
    expr: non-integer argument
    + v=
    

    Важность цитаты в строках

    Цитирование важно для расширения строки в bash. С их помощью вы можете контролировать, как bash анализирует и расширяет ваши строки.

    Существует два типа цитирования:

    • Слабый : использует двойные кавычки:
    • Сильный : использует одинарные кавычки:

    Если вы хотите использовать bash, чтобы расширить свой аргумент, вы можете использовать Weak Quoting :

    #!/usr/bin/env bash
    world="World"
    echo "Hello $world"
    #> Hello World
    

    Если вы не хотите использовать bash для расширения своего аргумента, вы можете использовать Strong Quoting :

    #!/usr/bin/env bash
    world="World"
    echo 'Hello $world'
    #> Hello $world
    

    Вы также можете использовать escape для предотвращения расширения:

    #!/usr/bin/env bash
    world="World"
    echo "Hello $world"
    #> Hello $world
    

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

    Понравилась статья? Поделить с друзьями:
  • Как создать backdoor в windows 10
  • Как создать iso образ windows 11 с обходом
  • Как создать active directory windows server 2012
  • Как создать iso образ windows 10 со своего компьютера
  • Как создать 2ой рабочий стол windows 10