- Как использовать $IFS в Bash?
- Предпосылки
- Пример 01: IFS разделяет строку с использованием пробела в качестве значения
- Пример 02: IFS разделяет строку с использованием символа в качестве значения
- Пример 03: IFS Split String
- Заключение:
- Что означает IFS = $ ‘\ n’ в сценариях bash?
- What is ifs in linux
- Example
- IFS Effect On The Values of «$@» And «$*»
- Bash IFS: its Definition, Viewing it and Modifying it
- What is IFS
- Viewing IFS
- No Quotes
- Single Quotes
- Double Quotes
- Viewing IFS as Backslash Escaped Characters
- printf %q “$IFS”
- cat -te
- od -[ab]c
- set | grep IFS
- Modifying IFS
- Modifying Using the Form $’string’
- Modifying Using Single or Double Quotes
- Backing up the Default
- Restoring the Default
- References
- Ahmed Amayem has written 90 articles
Как использовать $IFS в Bash?
Главное меню » Linux » Как использовать $IFS в Bash?
Предпосылки
Убедитесь, что у вас установлена и настроена система на базе Linux. Мы будем работать над системой Ubuntu 20.04 Linux. Войдите в систему под учетной записью пользователя Ubuntu, чтобы начать работу над IFS. Будет лучше, если вы войдете в систему под своей учетной записью root. После входа в систему запустите терминал командной строки в своей системе из области «Действия».
Пример 01: IFS разделяет строку с использованием пробела в качестве значения
В нашем первом примере мы поймем концепцию разделения строки в bash при использовании пробела в качестве значения-разделителя с помощью переменной IFS. Во-первых, мы должны создать в нашей системе файл bash. Мы можем создавать новые файлы в нашей системе Linux с помощью команды touch. Как показано ниже, мы создали файл bash file1.sh с помощью инструкции touch:
Откройте домашний каталог вашей системы Linux, используя значок папки, отображаемый в левом углу рабочего стола Ubuntu 20.04. В нем вы найдете свой недавно созданный файл bash «file1.sh». Откройте файл «file1.sh» и введите приведенный ниже сценарий. Во-первых, мы определили строку с именем «str» с некоторым строковым значением в ней. Затем мы определяем переменную-разделитель IFS как переменную, имеющую в качестве значения пробел. После этого мы использовали оператор чтения для сохранения и чтения разделенных данных в массив strarr с помощью флага «-a». Оператор ‘echo’ используется для печати строки строки вместе с подсчетом общего количества слов в массиве с использованием “$<#strarr[*]>”. Цикл «for» используется для печати значений массива в разделенной форме с использованием переменной «var». Обратная косая черта «\n» использовалась в строке печати вместе с переменной «var», чтобы разделить одну строку после каждого значения массива. Сохраните сценарий с помощью клавиши «Ctrl+S» и закройте файл, чтобы продолжить.
Пример 02: IFS разделяет строку с использованием символа в качестве значения
В вышеупомянутом примере вы видели, как разбить строковые переменные на части, используя пробел в качестве разделителя IFS. Теперь мы будем использовать символ для разделения строки с помощью разделителя IFS. Откройте командный терминал и создайте новый файл bash «file2.sh» в домашнем каталоге системы Linux, используя команду touch следующим образом:
Откройте домашний каталог вашей системы Linux. Вы найдете в нем свой недавно созданный файл. Откройте только что созданный файл и напишите представленный ниже код на bash. В строке 3 мы инициировали оператор «echo» для печати строки. Следующая строка считывает данные, введенные пользователем в терминале с использованием ключевого слова read. Затем мы определили разделитель «IFS» и установили запятую «,» в качестве его символьного значения. Другой оператор «read» был определен для чтения и сохранения значений, разделенных запятыми, в строке, которая вводится пользователем в массив «strarr». Наконец, мы инициировали три оператора echo для печати значений разделения, разделенных запятыми, в виде переменных, как показано на изображении. Сохраните и закройте этот файл.
Теперь нам нужно запустить этот сохраненный файл. Выполните показанную ниже команду bash, за которой следует имя файла в терминале, чтобы сделать это. Вы должны добавить строковое значение, которое должно содержать запятую «,» внутри значений, и нажать кнопку Enter. Теперь ваши данные сохранены в массиве strarr. Последние три строки показывают вывод операторов «echo». Как видите, каждый текст до и после запятой использовался как отдельное значение.
Пример 03: IFS Split String
Мы сделали оба предыдущих примера в файле bash. Теперь у нас будет иллюстрация использования «IFS» без создания файла bash. Для этого откройте командную оболочку. Во-первых, нам нужно создать строку «var» со строковым значением в ней. Эта строка содержит запятые после каждого слова.
Затем инициализируйте переменную IFS с помощью символьной запятой в качестве значения разделителя.
После этого мы использовали цикл «for» для поиска каждого слова из переменной «var», разделенного запятой-разделителем IFS, и печати его с помощью оператора «echo».
У вас будет результат ниже. Он покажет каждое слово строковой переменной «var» на новой строке из-за запятой-разделителя «», используемой в качестве символа разделения.
Заключение:
В этой статье вы узнали о различных методах разделения входных значений в bash, например, с помощью пробела или символа. Мы надеемся, что иллюстрации, упомянутые в этой статье, помогут вам разбить каждую строку с помощью разделителя IFS.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
Что означает IFS = $ ‘\ n’ в сценариях bash?
В начале сценария оболочки bash находится следующая строка:
В чем смысл этой коллекции символов?
IFS расшифровывается как «внутренний разделитель полей». Он используется оболочкой для определения того, как выполнять разбиение слов, то есть как распознавать границы слов.
Попробуйте это в оболочке, такой как bash (другие оболочки могут обрабатывать это по-разному, например, zsh):
Значение по умолчанию для IFS состоит из пробельных символов (если быть точным: пробел, табуляция и новая строка). Каждый символ может быть границей слова. Таким образом, со значением по умолчанию IFS , цикл выше напечатает:
Другими словами, оболочка считает, что пробел является границей слова.
Теперь попробуйте установить IFS=: перед выполнением цикла. На этот раз результат:
Теперь оболочка также разбивается mystring на слова — но теперь она рассматривает только двоеточие как границу слова.
Первый символ IFS — специальный: он используется для разделения слов в выводе при использовании специальной $* переменной (пример взят из Руководства по расширенному написанию сценариев Bash , где вы также можете найти дополнительную информацию о специальных переменных, подобных этой):
Обратите внимание , что в обоих примерах, оболочка будет по- прежнему относиться все символы : , — а ; также границы слов. Единственное, что меняется, это поведение $* .
Еще одна важная вещь, которую нужно знать, это то, как обрабатываются так называемые «пробелы IFS» . По сути, как только IFS включаются пробельные символы, начальные и конечные пробельные символы удаляются из строки, которая должна быть разделена перед обработкой, а также последовательность последовательных пробельных символов также разделяет поля. Однако это относится только к тем пробельным символам, которые фактически присутствуют в IFS .
Например, давайте посмотрим на строку «a:b:: c d » (завершающий пробел и два пробела между символами c и d ).
- С IFS=: он будет разделен на четыре поля: «a» , «b» , «» (пустая строка) и » c d » (опять же , два пространства между c и d ). Обратите внимание на начальные и конечные пробелы в последнем поле.
- С IFS=’ :’ , она будет разделена на пять полей: «a» , «b» , «» (пустая строка), «c» и «d» . Нет ни одного начального и конечного пробела.
Обратите внимание, что во втором примере несколько последовательных пробельных символов разделяют два поля, а несколько последовательных двоеточий — нет (поскольку они не являются пробельными символами).
Что же касается IFS=$’\n’ , то есть ksh93 синтаксис также поддерживается bash , zsh , mksh и FreeBSD sh (с вариациями между всеми оболочками). Цитирую man-страницу bash:
Слова вида $ ‘string’ обрабатываются специально. Слово расширяется до «строки», символы с обратной косой чертой заменяются в соответствии со стандартом ANSI C.
\n является escape-последовательностью для новой строки, поэтому в IFS конечном итоге устанавливается один символ новой строки.
Источник
What is ifs in linux
From the bash man page:
The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters space and tab are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs.
- The default value of IFS is a space, a tab, and a newline.
Example
Create a text file called /tmp/domains.txt as follows:
Create a shell script called setupapachevhost.sh as follows:
Save and close the file. Run it as follows:
- The read command reads input from $file file.
- Each line of $file is broken into tokens with the help of $IFS.
- The value of IFS (|) are used as token delimiters or separator for each line.
- Each line is divided into four fields as domain, ip, webroot, and ftpusername.
- The while loop is used to read entier $file.
- The first token (Apache virtual hosting domain name) is saved to the actual variable called $domain.
- The second token (Apache ip address) is saved to the actual variable called $ip.
- The third token (Apache DocumentRoot) is saved to the actual variable called $webroot.
- The fourth token (FTP server username) is saved to the actual variable called $ftpusername.
IFS Effect On The Values of «$@» And «$*»
- $@ and $* are special command line arguments shell variables.
- The $@ holds list of all arguments passed to the script.
- The $* holds list of all arguments passed to the script.
- Create a shell script called ifsargs.sh:
Save and close the file. Run it as follows:
- As you can see, the values of $@ and $* are same.
- However, the values of «$@» and «$*» are different (note double quotes).
- Edit ifsargs.sh as follows
Save and close the file. Run it as follows:
Источник
Bash IFS: its Definition, Viewing it and Modifying it
When writing a bash shell script it is important to understand how IFS (Internal Field Separtor) works and how it can be modified/changed.
What is IFS
As mentioned in the man bash pages IFS is defined as follows:
So basically IFS defines which characters bash will use to delimit words. Naturally whitespace is the default, . Of course, as is usual in the English language, the whitespace is not considered part of the word and is ignored.
Viewing IFS
To access the IFS characters we just need to print out the characters in the variable $IFS . As mentioned in Bash Backslash Escaped Characters and Whitespace Explained with Examples the backslash escaped characters are different from what they represent i.e. is not the same as \n . The default IFS characters are not tn . This will be proven in the following examples.
No Quotes
Since IFS , by default, is just whitespace we won’t really see much when we try to print it out:
As we can see, hello world is printed without a in between. The reason for this is simple. After $IFS was expanded to , bash used word splitting on the whole line. So bash had to split the following line:
So after word splitting, echo had only two arguments: hello and world . The man bash pages have more to add:
Notice how the characters in IFS are not considered part of the word.
Single Quotes
This happened because single quotes take away the special meaning of the $ , as explained here.
Double Quotes
This time it worked because the double quotes don’t take away the meaning of the $ so $IFS was expanded. The double quotes preserve the whitespace and prevents word splitting here as mentioned here.
Viewing IFS as Backslash Escaped Characters
Now that we have established that IFS is not the backslash escaped characters, we face the problem that we can’t see the whitespace. It would be nice if we could convert the whitespace to backslash escaped characters so we know what they are. The following methods work:
printf %q “$IFS”
The %q option is a cool feature of printf as mentioned in the man bash pages:
Notice that I had to use the double quotes so that the whitespace appears. Using single quotes or no quotes would not work as mentioned earlier.
cat -te
Like printf , cat has options that allow for whitespace characters to be represented with something else as mentioned in the man cat pages:
So we will have to translate ^I to t and $ to n . The -n flag of echo removes the final newline that is usually added by echo .
od -[ab]c
First we piped the IFS characters to od , but without the last newline that echo adds, by adding the -n flag. Then od has the following options as explained in its man pages:
So really the one we want is the c , but we won’t see the space very clearly so it is good to have the other two as well.
set | grep IFS
Let’s not forget that IFS is a shell variable after all, hence we should be able to see the characters of IFS with all the other shell variables. Shell variables can be seen using set :
Of course since there are so many shell variables we will pipe the output into grep and filter for IFS :
Remember that set is conveniently printing out the value in a way that can be used to set the variables, it does not mean that the characters of IFS are tn . They are as explained earlier
Modifying IFS
When modifying IFS and using whitespace characters we have to be careful how we quote the new string. If we want to use backslash escaped characters then we have to use the form $’string’ as mentioned here. If we want to use the actual characters then we have to use single or double quotes.
Modifying Using the Form $’string’
Modifying Using Single or Double Quotes
Backing up the Default
Whenever we change the IFS it is usually a good idea to save the default first and then restore the IFS to its default after you are done:
Restoring the Default
References
- fvue’ wiki on IFS
- Hikaru‘s answer in this thread
- man bash pages
- man cd pages
- man cat pages
0 people found this article useful This article was helpful
This article was helpful
0 people found this article useful
Ahmed Amayem has written 90 articles
A Web Application Developer Entrepreneur.
Nice analysis. Thanks Ahmed.
Incidentally, you can return the IFS back to its default setting by unsetting it:
unset IFS
If you then try to print it, it will not contain anything (it will be a null string), but in fact bash now uses its internal default of for IFS.
I’ve been enjoying a number of your articles and should mention that anywhere you backslash-escape characters in the main text or blockquoted text or code, the filter you used to generate your webpages is swallowing the backslashes and merely displaying the character alone. For example “n” (newline) becomes shown as just “n”. Perhaps you need to double-escape them, like this: \n
Thanks for the info and the feedback.
I used to use ghost as my blogging platform and it was working well. After I switched to WP it seems my escaped characters were removed in the source text itself. I just tested to see if the problem was at pageload, and luckily the page loaded fine with the “. This will probably take some time to rectify, but it is a very important catch.
Источник