[For beginners] How to use for statements on Linux (variables, etc.)

Introduction

In this article, I will write about the parts that I didn't understand when trying to use the for statement (especially about how to use variables).

How to use the for statement in the first place

Basic form of for statement


for variable in list of values
do
processing
done

There are the following ways to use the for statement on Linux.

1. Load as a shell script

Create a file with a suitable editor (such as Notepad) (extend to **. Sh **), write a for statement in the above form, and read it on Linux. Write the characters #! / Bin / bash on the first line of the file.

Make with notepad etc. (hoge.sh)


#!/bin/bash
for i in 1 2 3
do
echo $i        ##1 2 3 is output to the screen
done

To read the created file (shell script), just type ** the file name on the Linux screen and it's OK . However, since you must specify the file path, use ". / File name " (. ** refers to the ** current directory *). ( Place the created file in the current directory in advance)

Output result


$ ./hoge.sh
1
2
3

2. Write on the command line (multiple lines)

You can copy and paste the contents written in Notepad as above on the Linux screen. In that case, the > mark is automatically added for each line break.

Command & output result


$ for i in 1 2 3
> do
> echo $i
> done
1
2
3

3. Write on the command line (1 line)

Instead of changing lines, you can also write in one line by adding ; to ** for line ** and ** before ** done **.

Command & output result


$ for i in 1 2 3; do echo $i; done
1
2
3

Reference: Bash on the command line in one line (for statement / if statement)

In the following explanation, we will use the for statement by ** 2 method **.

How to use variables in for statements

It's basically the same as using variables in a shell script. If you look up "** shell script variables **", there are many sites, so please check it out!

Introduction of basic commands for shell scripts for beginnersSummary of basic knowledge of shell scripts -Use of variables-Linux Mint memo

I would like to briefly explain some cases.

1. Use a value in "$ variable name"

The value of the ** variable ʻi** can be used in **$ i` **. (See example above)

2. If a character string is adjacent to a variable, use "$ {variable name}"

If the string ** $ i ** is consecutive, it must be $ {i}.

$ for i in 1 2 3
> do
> echo $ixxx
> echo ${i}xxx
> done
             ## "ixxx"Does not exist, so nothing is output.
1xxx         ## "Value of variable i(=1)" + "xxx"Is output.

2xxx

3xxx

3. Enclose variables in " " instead of ''

Double quote"" ...Read the contents of the variable (ex. "$i" -> 1)
Single quote'' ...Display the character string as it is (ex. '$i' ->  $i)
Backticks`` ...Read as command (ex. `cat test.txt` -> test.Output the contents of txt)

On Linux, there are differences between '' " " as above, so be sure to use ** " " ** when enclosing variables in quotation marks **.

$ cat test01.txt
1xxxxxxxxxx
xxx2xxxxxxx
xxxxx3xxxxx
xxxxxxxx4xx
xxxxxxxxxx5

##Extract only rows containing 1 4 5
$ for i in 1 4 5
> do
> cat test01.txt | grep "$i"
> done
1xxxxxxxxxx
xxxxxxxx4xx
xxxxxxxxxx5

## $Extract lines containing the string i (no output)
$ for i in 1 4 5
> do
> cat test01.txt | grep '$i'
> done

Reference: [bash] Difference between "" "," '", and" `"-Rather rice school

How to write a list of values

A rough list looks like this (I think there are many others).

##Move i by 1 2 3 4 5
for i in 1 2 3 4 5
for i in {1..5}
for i in `seq 1 5`
for i in `seq 5`
for ((i=1; i<=5; i++))

##Move i by 2( 1 3 5 7 9 )
for ((i=1; i<=10; i=i+2))         ## (First value;i condition;How to increase i(or how to reduce))
for ((i=1; i<=10; i+=2))

##Substitute a letter for i
for i in aa bb cc

##Read each line in the file(Note that the loop will be separated even if it is blank.;See below)
for i in `cat test.txt`

##Specify a file in the directory
for i in *.txt
for i in `ls`

Reference: [For] Command (Application Part 2) -Repeat processing in combination with the command execution result [For] Command (Application Part 3) -Repeat processing by specifying the number of times

Bonus: read each line in the file (while read line)

It seems that the method of reading with the while statement is more major than the for statement (→ [Refer to the postscript](#Additional note)). There are several patterns, but be aware that if the last line of the file to be read does not have a line break, only the last line may not be read depending on the method.

Reference: Copy and paste is possible | Process by line with bash / while read line: 5 patterns Solution for BASH while read not processing last line

As far as I've investigated, the method passed in here document (the method below) can avoid the problem, so I personally think that this method is good.

$ cat test02.txt
1
2
3
4
5    ##No line breaks

##Last line not read
$ cat test02.txt | while read line
> do
> echo line : $line
> done
line : 1
line : 2
line : 3
line : 4

##Read up to the last line
$ while read line
> do
> echo line : $line
> done << Hear
> `cat test02.txt`
> Hear
line : 1
line : 2
line : 3
line : 4
line : 5

Postscript

As explained in Link above, in the case of for statement, the loop is separated not only by line breaks but also by blanks, so each line If you want to process each, it is more versatile to use while read line.

$ cat test02.txt
1 x
2xx
3
4
5

##for is separated even if it is blank
$ for i in `cat test02.txt`
> do
> echo line : $i
> done
line : 1
line : x
line : 2xx
line : 3
line : 4
line : 5

##while is not separated by spaces
$ while read line
> do
> echo line : $line
> done << Hear
> `cat test02.txt`
> Hear
line : 1 x
line : 2xx
line : 3
line : 4
line : 5

Recommended Posts

[For beginners] How to use for statements on Linux (variables, etc.)
[Python] Organizing how to use for statements
How to use data analysis tools for beginners
[For beginners] How to use say command in python!
Beginners! Basic Linux commands and how to use them!
How to use C216 Audio Controller on Arch Linux
[Tips] How to use iPhone as webcam on Linux
How to use Dataiku on Windows
Notes on how to use pywinauto
How to install VMware-Tools on Linux
Notes on how to use featuretools
How to use homebrew on Debian
Notes on how to use doctest
How to install aws-session-manager-plugin on Manajro Linux
How to use mecab, neologd-ipadic on colab
[Linux] How to use the echo command
I want to use Linux on mac
How to use the Linux grep command
How to update php on Amazon linux 2
How to use Google Assistant on Windows 10
How to display emoji on Manjaro Linux
Memorandum on how to use gremlin python
How to install packages on Alpine Linux
How to install Anisble on Amazon Linux 2
How to install Windows Subsystem For Linux
How to update security on CentOS Linux 8
How to use Pylint for PyQt5 apps
How to install php7.4 on Linux (Ubuntu)
How to use "deque" for Python data
How to find large files on Linux
How to use fingerprint authentication for KDE
[C language] How to use the crypt function on Linux [Password hashing]
How to use MkDocs for the first time
How to make Spigot plugin (for Java beginners)
How to use Template Engine for Network Engineer
How to use Python Kivy ④ ~ Execution on Android ~
How to use Tweepy ~ Part 2 ~ [Follow, like, etc.]
How to create a shortcut command for LINUX
How to install Camunda Modeler on Manjaro Linux
How to build Java environment on Ubuntu (Linux)
How to make Python faster for beginners [numpy]
[For beginners] How to study programming Private memo
How to find the correlation for categorical variables
Useful for changing permissions on Linux! How to count up to 31 with one hand.
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use Pandas 2
How to use Virtualenv
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib