Специальные символы командной строки linux

Содержание
  1. Спецсимволы в bash
  2. Bash Scripting: Symbols
  3. Symbol: In this case, the file.txt is taken as the input, and the cat command then cats it out. Symbol: > This symbol, known as the file redirection operator, is typically used to redirect the contents of a command/file to another by overwriting it. echo “hello world’ > file.txt Here, the > symbol is similar to 1>. This is so because the 1 is a file descriptor for the standard output. Please note that the file descriptors are as follows: 1 — Standard output, stdout In the previous scenario, the single forward arrow was equivalent to 1>. However, we can also write 2> to forward it to the standard error. Here, the 2> means that the error will be dumped into file2.txt. Symbol: >> The symbol >> is used to append and not to replace! The file redirection operator replaces or overwrites everything while the >> is used to append. echo “this is the second line” >> file.txt echo “this is the third line” >> file.txt The latter will append the two lines to the file called file.txt. The result of file.txt will then be as follows: Symbol: # The hashtag is used to add one-line comments into scripts. These comments are not executed/run. # this will dump the line into the file echo “this is a file ” > file.txt Unlike the #, which is a one-liner, the multi-line comments look more like this; This is the comments section Symbol: $# The symbol $# is used to retrieve the length or the number of arguments passed via the command line. When the symbol $@ or simply $1, $2, etc., is used, we ask for command-line input and store their values in a variable. The symbol $# is used to retrieve the total number of arguments passed. The latter should chuck out a value of 2 because there are 3 elements (hello, world, and again). Symbol: &> This symbol redirects both the standard output and the standard error. In this case, the &> symbol redirects both the standard output and the standard error to the file called file.txt. Thus, both the output generated and the error generated is placed in the same file. Symbol: \ You need to compare the string length or character lengths; this can be done via the symbols \< and \>. These two symbols are used to compare character lengths. In this case, the word stored in a – or cat – has a character length of 3, while the word stored in b – or lynx -has a character length of 4. Thus the answer should be that “a is shorter than b.” Symbol: ^^, ^ and ,, Some symbols function to change the case of the characters. ^^ — to turn all characters to uppercase ^ — to turn the first letter to uppercase ,, — to turn all characters to all lowercase Symbol: $@ or $* The symbol $@ is equivalent to $* which is equivalent to $1 $2 $3 $4… # the latter is equivalent to echo $@ In this example, the $1, $2, $3, $4, and $5 are inputs from the command line. Alternatively, we could have written the following: Symbol: $? This particular symbol – $? – is used to get the exit status of the command previously passed. echo “hello world” > file.txt An exit status of 0 indicates that the process was completed successfully. Symbol: $$ The symbol $$ stores the PID of the current shell. In my case, it printed out the value 2443. This is the PID of the shell. Symbol: 2>&1 The symbol 2>&1 redirects both the standard output and the standard error to the standard output. In this case, all the standard output and if any error is generated, the standard error is both directed into the file called file.txt. Bash scripting is a key scripting language that can be used to automate tasks. During bash scripting, we encounter much code, but we also encounter special characters or symbols that are unique to bash. These symbols each have a particular role in bash scripting, and they aren’t always obvious. In this tutorial, we reviewed a few key symbols used while writing bash scripts. Obviously, there are many symbols out there; however, some are encountered so frequently that it might be necessary to know them while bash scripting. So go forth, fearless of the symbol from here onwards! About the author Omar Farooq Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces. Источник
  4. Symbol: >
  5. Symbol: >>
  6. Symbol: #
  7. Symbol: $#
  8. Symbol: &>
  9. Symbol: ^^, ^ and ,,
  10. Symbol: $@ or $*
  11. Symbol: $?
  12. Symbol: $$
  13. Symbol: 2>&1
  14. About the author
  15. Omar Farooq
Читайте также:  Открыть содержимое файла linux

Спецсимволы в bash

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

\ Экранирование. Отменяет специальное значение следующего символа
\\ Символ «\»

# Комментарий, не работает в кавычках и в некоторых подстановках переменных и преобразовании основания чисел
echo «Это #не комментарий»
echo ‘Это # не комментарий’
echo Это \# не комментарий
echo Это # Вот комментарий.
echo $ #Специальная переменная
echo $(( 2#101011 )) #Преобразование системы счисления в арифметической подстановке.

; Разделитель команд в строке
echo hello; echo world

;; Разделитель альтернатив в операторе case
case «$VARiable» in
abc) echo «$VARiable = abc» ;;
xyz) echo «$VARiable = xyz» ;;
esac

. Аналог команды source (#include в С++). Выполняет скрипт в текущем интерпретаторе.
. myconf

«..» Двойные кавычки, отменяют действие спецсимволов кроме $ `..` и \

‘. ‘ Апострофы, отменяют действие всех спецсимволов в том числе и \, по этому нельзя включить апостроф в строку ограниченную апострофами

: Нулевая команда, всегда возвращает нулевой код ответа. В сочетании с перенаправлением «>» создает файл, или обнуляет существующий. В сочетании с перенаправлением «>>» создает файл, или изменяет время модификации существующего
:> data.xxx # File “data.xxx” now empty.
(можно и без двоеточия)

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

* Шаблон заменяющий любую последовательность символов
? Шаблон заменяющий ровно один символ
[xyz] Шаблон заменяющий один из перечисленных символов
Подстановка одного из вариантов в шаблон. В скобках не должно быть неэкранированных пробелов
grep Linux file*. # Ищет слово “Linux” в файлах вида “fileA.txt”, “file2.txt”, “fileR.html”, “file-87.htm”, etc.

$ Подстановка значения переменной, арифметического выражения или стандартного вывода программы. Если значение содержит пробелы, то при подстановке оно разбивается на отдельные аргументы.
$A содержимое переменной A
$$ PID процесса
$? Код возврата из последней выполненной программы или функции, а также код возврата самого скрипта
$((2*2)) подстановка результата вычисления арифметического выражения
$(cmd) подстановка стандартного вывода программы
`. ` тоже, что и $(. ) – подстановка стандартного вывода программы

Читайте также:  Virtualbox linux debian image

Пример: A=EE; echo $A $(echo QQ) $((7+5))
Результат: EE QQ 12
Ошибка: $A=ZZ
Результат: bash: EE=ZZ: command not found

(. ) Группировка команд
(A=hello; echo $A)
Для выполнения группы в скобках запускается новый интерпретатор
A=123
(A=321)
echo A = $A # A = 123
# «A» внутри скобок – локальная переменная.

(. ) Создание массива ( только в bash версии > 2)
Array=(element1 element2 element3)

[] Элемент массива ( только в bash версии > 2)
Array[1]=slot_1
echo $

— подстановка чисел от 1 до 10
— подстановка символов от «c» до «n»

<. >Создание безымянной функции, удобно для перенаправления ввода/вывода нескольких команд в один файл. В отличие от настоящей функции видимости переменных не изменяется.
PACK=mysql
echo
echo «Archive Listing:»
rpm -qpl $ # Список фалов в пакете rpm
echo
rpm -i —test $ # Проверка, установлен ли пакет.
> > «$.txt» #И весь вывод в один файл.

[. ] Встроенная функция test для вычисления логических выражений

((. )) Арифметическая подстановка, вычисляет арифметическое выражение в стиле языка Си внутри скобок

& — запуск программы в фоновом режиме
bash$ sleep 10 &
[1] 850
[1]+ Done sleep 10

Источник

Bash Scripting: Symbols

On Linux, the terminal is everything, it’s where we pass commands, and it’s where we pass scripts. Therefore, one of the most important scripting languages is bash. Bash scripting is used to automate the boring tasks in Linux. In order to automate tasks, commands are written within the script and given an extension of .sh. As part of the commands, certain symbols are used as well. These symbols are unique to bash, and each has its own specific meaning. In this tutorial, we will review the various symbols encountered during bash scripting and their specific meaning.

Symbol:

In this case, the file.txt is taken as the input, and the cat command then cats it out.

Untitled_14

Symbol: >

This symbol, known as the file redirection operator, is typically used to redirect the contents of a command/file to another by overwriting it.

echo “hello world’ > file.txt

Untitled

Here, the > symbol is similar to 1>. This is so because the 1 is a file descriptor for the standard output. Please note that the file descriptors are as follows:

1 — Standard output, stdout

In the previous scenario, the single forward arrow was equivalent to 1>. However, we can also write 2> to forward it to the standard error.

Here, the 2> means that the error will be dumped into file2.txt.

Untitled2

Symbol: >>

The symbol >> is used to append and not to replace! The file redirection operator replaces or overwrites everything while the >> is used to append.

echo “this is the second line” >> file.txt

echo “this is the third line” >> file.txt

The latter will append the two lines to the file called file.txt. The result of file.txt will then be as follows:

Untitled3

Symbol: #

The hashtag is used to add one-line comments into scripts. These comments are not executed/run.

# this will dump the line into the file

echo “this is a file ” > file.txt

Untitled4

Unlike the #, which is a one-liner, the multi-line comments look more like this;

This is the comments section

Untitled5

Symbol: $#

The symbol $# is used to retrieve the length or the number of arguments passed via the command line. When the symbol $@ or simply $1, $2, etc., is used, we ask for command-line input and store their values in a variable. The symbol $# is used to retrieve the total number of arguments passed.

The latter should chuck out a value of 2 because there are 3 elements (hello, world, and again).

Untitled7

Symbol: &>

This symbol redirects both the standard output and the standard error.

In this case, the &> symbol redirects both the standard output and the standard error to the file called file.txt. Thus, both the output generated and the error generated is placed in the same file.

Untitled6

Symbol: \

You need to compare the string length or character lengths; this can be done via the symbols \< and \>. These two symbols are used to compare character lengths.

In this case, the word stored in a – or cat – has a character length of 3, while the word stored in b – or lynx -has a character length of 4. Thus the answer should be that “a is shorter than b.”

Untitled8

Symbol: ^^, ^ and ,,

Some symbols function to change the case of the characters.

^^ — to turn all characters to uppercase

^ — to turn the first letter to uppercase

,, — to turn all characters to all lowercase

Untitled9

Symbol: $@ or $*

The symbol $@ is equivalent to $* which is equivalent to $1 $2 $3 $4…

# the latter is equivalent to echo $@

In this example, the $1, $2, $3, $4, and $5 are inputs from the command line. Alternatively, we could have written the following:

Untitled_10

Symbol: $?

This particular symbol – $? – is used to get the exit status of the command previously passed.

echo “hello world” > file.txt

An exit status of 0 indicates that the process was completed successfully.

Untitled_11

Symbol: $$

The symbol $$ stores the PID of the current shell.

In my case, it printed out the value 2443. This is the PID of the shell.

Untitled_12

Symbol: 2>&1

The symbol 2>&1 redirects both the standard output and the standard error to the standard output.

In this case, all the standard output and if any error is generated, the standard error is both directed into the file called file.txt.

Untitled_13

Bash scripting is a key scripting language that can be used to automate tasks. During bash scripting, we encounter much code, but we also encounter special characters or symbols that are unique to bash. These symbols each have a particular role in bash scripting, and they aren’t always obvious. In this tutorial, we reviewed a few key symbols used while writing bash scripts. Obviously, there are many symbols out there; however, some are encountered so frequently that it might be necessary to know them while bash scripting. So go forth, fearless of the symbol from here onwards!

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

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