Linux bash перенос строк

How can I have a newline in a string in sh?

What should I do to have a newline in a string? Note: This question is not about echo. I’m aware of echo -e , but I’m looking for a solution that allows passing a string (which includes a newline) as an argument to other commands that do not have a similar option to interpret \n ‘s as newlines.

13 Answers 13

If you’re using Bash, you can use backslash-escapes inside of a specially-quoted $’string’ . For example, adding \n :

STR=$'Hello\nWorld' echo "$STR" # quotes are required here! 

If you’re using pretty much any other shell, just insert the newline as-is in the string:

Bash recognizes a number of other backslash escape sequences in the $» string. Here is an excerpt from the Bash manual page:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: \a alert (bell) \b backspace \e \E an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \' single quote \" double quote \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \cx a control-x character The expanded result is single-quoted, as if the dollar sign had not been present. A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted. 

Источник

How to echo a New Line in Bash Shell Scripts

Learn various ways of displaying a new line in the output of echo command in Linux.

The echo command automatically adds a new line at the end. That’s cool.

But what if you want to display just an empty new line? Or if you want to output something that contains a new line?

Читайте также:  Установка asterisk astra linux

The good news is that, echo lets you use the newline character \n to print a new line within the same output line if you use the -e option:

echo -e "Name\nAddress\nPhone Number"

If you run the above command, you’ll get this output:

Name Address Phone Number

That’s nice, right? Let’s have a more detailed look into it.

Display new line with -e flag of echo command (recommended)

A newline is a term we use to specify that the current line has ended and the text will continue from the line below the current one. In most UNIX-like systems, \n is used to specify a newline. It is referred to as newline character.

The echo command, by default, disables the interpretation of backslash escapes. So if you try to display a newline using the ‘\n’ escape sequence, you will notice a problem.

$ echo Hello\nworld Hellonworld $ echo 'Hello\nworld' Hello\nworld

Enclosing text in single quotes as a string literal does not work either.

That was not an expected output. To actually print a new-line, you can use the ‘-e’ flag to tell the echo command that you want to enable the interpretation of backslash escapes.

$ echo -e 'Hello\nworld' Hello world

Nice, that’s what you are looking for.

Let me some other ways to display the newline character.

echo a variable containing new line

You can store a string in a bash variable and then echo it using the ‘-e’ flag.

$ str="Hello\nworld" $ echo -e $str Hello world

Use the ‘$’ character instead of -e flag

The dollar symbol, ‘$’ is called the «expansion» character in bash. This is the character that I used in the earlier example to refer to a variable’s value in shell.

If you look closely at the snippet below, you will realize that the expansion character, in this case, acts to hold a temporary value.

$ echo Hello$'\n'world Hello world

Or, you can use the whole string as a ‘temporary variable’:

$ echo $'Hello\nworld' Hello world

I would prefer to use the -e flag, though.

echo your echo to print something with new line

When you echo a piece of text, the echo command will automatically add a newline (and here is how you can prevent it) to the end of your text.

This means that you can chain multiple echo commands together to cause a newline.

$ echo Hello; echo world Hello world

Use printf to print newline in Bash shell

printf is another command line tool that essentially prints text to the terminal, but it also allows you to format your text.

The usage is very simple and similar to echo but a bit more reliable and consistent.

$ printf 'Hello\nworld\n' Hello world

As expected, you have a newline without using any flags.

Читайте также:  Linux memory usage details

Conclusion

Personally, I would prefer sticking with the -e flag or go for the printf command for displaying the new lines in output. I recommend you to do the same but feel free to experiment.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Quick start bash scripting (ru)

softAdd/bash-basics

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

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

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

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

Для того, чтобы воспользоваться вторым способом, необходимо сначала выдать файлу правильные права:
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

user=someUsername if grep $user /etc/passwd then echo "The user $user Exists" fi
user=someUsername if grep $user /etc/passwd then echo "The user $user Exists" else echo "The user $user doesn’t exist" fi
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

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

yaourt -S \ package1 \ packege2 \ package3

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

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 (( i=1; i  10; i++ )) do echo "number is $i" done
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

В секции 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
В параметрах мы передаем утилите адрес файла скрипта. Исполняемость — это обязательный параметр для всех способов.

Источник

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