About Linux

Premise

Main subject

Features of Linux

Kernel and userland

Software is divided into basic software and applied software. The basic software is further divided into two.

  1. Kernel The kernel is the core of the operating system and is responsible for the most core functions, such as interacting directly with the hardware. The kernel is responsible for absorbing hardware differences and allowing programs to run the same on any hardware.

2, user land The part other than the kernel required for the OS to operate. Refers to basic software such as file stems, file operation commands, and shells.

shell

The shell understands and executes the command entered. The shell itself has two main functions.

  1. Accept command input 2, execution of shell script A shell script is for automating command input. Create one command line by line in one file. Command execution can be automated by executing the created shell script. You can also run the created shell script when the server starts, or every few hours.

Basic commands

Browse files and directories (ls)

#Format
ls [option][File]

#option
-a
// .All hidden files starting with (ALL) are output

-l
//Output in Long format

-t
//Sort and output according to the last update time (Time)

-r
//Sort and output in reverse order

-la
//Display in long format including hidden files

-lt
//List files sorted by file modification time

* </ code> indicates an arbitrary character string, and no matter how many characters are entered between them, it will be output as a search result. Example) Displaying a list of files ending in conf

$ cd /etc
$ ls *.conf

? </ Code> is when the number of characters in the file name is known.

$ cd /etc
$ ls ???.conf

Copy file (cp)

$ cp [option]Copy source Copy destination

-i
//Confirm whether to overwrite the file when performing the process. It is used to apologize and prevent overwriting.

-r
//Copy the directory.-With the r option, you can copy to all files and directories in the directory.

-p
//Save the information of the original file. If you copy with the cp command, the new files will be copied with all the nice contents. Use this when you want to make a copy while preserving the old information without creating new content.

Move file (mv)

$mv move source file move destination file

-i
//Confirm when processing. File overwrite etc.

-f
//Forcibly execute the process.

Delete file (rm)

$rm file name

-i
//Confirm when processing. File overwrite etc.

-f
//Forcibly execute the process.

-r
//Target the dictation. Delete files and directories in the directory as well.
  • On UNIX-based OS including Linux, files deleted once cannot be restored. Also, the rm command cannot delete a directory (without options).

Create directory (mkdir)

$mkdir directory name

#option
-p
//It also creates a directory above the specified directory.

#When creating 3 directories at once
$ mkdir -p dir1/dir2/dir3

Delete directory (rmdir)

$rmdir directory name

#option
-p
//Deletes directories up to the specified hierarchy at once. If you execute the rmdir command without options, only the lowest level directory is deleted. However, in either case, the target directory must be empty.

#When creating 3 directories at once
$ mkdir -p dir1/dir2/dir3

View file contents (cat)

$cat file name

-n
Display with line numbers added.

Display using pager

$more file name

#Next command
Space Go to the next page
b Return to the previous screen
f Go to the next screen
/Word Search for a word. Jump search results with n key
q Quit the pager command (quit)

$less file name

#Next command
Space Go to the next page
b Return to the previous screen
f Go to the next screen
↑ Go to the previous line
↓ Go to the next line
/Word Search for a word. Jump search results with n key
q Quit the pager command (quit)

File search (find)

$find path-name file name

Show command path (which)

$which command name
  • If the directory where the command exists is not included in the PATH environment variable, the result of which command will be an error. For example, the path to a command that requires administrator privileges may not be confirmed by the which command because it is not set by a general user.

Regular expressions and pipes

grep command

The grep command retrieves data in a file. You can also search for data entered from standard input by using | grep </ code>.

$ grep [option]Search conditions[Specified file]

#option
-e
//Treat the character string as a search pattern.

-i
//Do not distinguish between uppercase and lowercase letters in both the search pattern and the input file.

-v
//Select rows that do not match your search pattern.

Regular expressions

#Symbols and meanings used in regular expressions

^Represents the beginning of a line
$Represents the end of a line
.Means any letter
*Means 0 or more repetitions of the previous character
[...] ..Means any one character in
[^...] ..Means that the character of
\ Escape regular expression symbols
#Regular expression usage example

^Lines starting with a a
b$Lines ending in b
a.b There is one character between a and b
[ab]ab a or b followed by ab(aab,bab)
[^ab]ab a or not starting with b (not) followed by ab (eg xab,zab etc.)

Basic command 2

Change file time stamp (touch)

The file always has a time stamp (last modified date). You can check the time stamp by adding the -l option of the ls command. The touch command changes the last update time. If the file with the specified file name does not exist, an empty file is created.

$ touch [Option name]file name

#option
-t
//Specify the modification time of the file.

Get part of the file (head, tail)

$ head [Option name]file name

#option
-n lines
//Outputs the specified line from the beginning as standard.

-c bytes
//Outputs the specified bytes from the beginning as standard.
  • Head outputs the first part of the file as standard. If no option is added, the first 10 lines are output as standard.
$ tail [Option name]file name

#option
-n lines
//Outputs the specified line from the end as standard.

-c bytes
//Outputs the specified bytes from the end as standard.

-f
//Changes can be monitored in real time.
  • Tail outputs the end of the file as standard. If no option is added, the last 10 lines are output as standard.

Text file sort

$ sort [option]file name

#option
-r
//Sort in reverse order.

-k n
//Sort the data in the nth column.

-n
//Sort as a number.

Data sort in column n (-k)

With the -k option, specify the column number to be used as the sort key.

$ sort -k 2 score

Clear duplicate lines (uniq)

If the same content as the previous line is found by using the uniq command, the target line is not output. Consecutive lines with the same content can be combined into one line.

$uniq filename

String replacement (tr)

You can use the tr command to replace data from standard input character by character (TRanslate).

$tr character string 1 character string 2

File comparison (diff)

$ diff [option]File 1 File 2

#option
-c
//Output the difference in context diff format.

-u
//Output the difference in unified diff format.

vi editor

When you open a file with vi, it is called command mode, and there are a mode that allows you to move lines and pages by paging, edit operations such as deleting lines, copying, cutting, and pasting, and an insert mode that accepts character input. is there.

Open file

$ vi [file name]

Close file

To close a file opened using the vi command, press ESC </ code> and then type : q </ code>.

  • Abbreviation for quit

Save the file

To save a file opened using the vi command, press ESC </ code> and then type : w </ code>.

  • Abbreviation for write

Save the file and exit

To close a file after saving it with the vi command, press ESC </ code> and then type : wq </ code>.

Force close without saving the file

To close a file opened with the vi command without saving it, press ESC </ code> and then type : q! </ Code>.

Enter text

The insert mode for entering a character string must be switched to the insert mode with a command. There are various commands for switching to insert mode, but to enter a character string, enter the i command </ code> or the a command </ code>.

  • If you make a mistake, you can delete the one character before the cursor with Delete or BS.

Move cursor

When editing a text file, you may notice a typo or make changes later, so you may want to correct the text you have already entered. If there is a character to add, move the cursor to the place you want to modify and enter the character.

*** Move cursor left and right *** Enter h </ code> down to move the cursor to the left with vi, or l </ code> to move the cursor to the right.

*** Move cursor up and down *** You can move the cursor up and down to j </ code> down and k </ code> up.

*** Move to the beginning of a line using a command *** You can move to the beginning of the current line by executing the 0 </ code> command.

*** Move to end of line using command *** You can move to the end of the current line by executing the $ </ code> command.

Move page by page

The vi command can edit small to large files. Use commands to move the screen back and forth by page (default specified number of lines) for quick editing.

To move to the next page, use the "Ctrl" f command </ code>, and to move to the previous page, use the "Ctrl" b command </ code>.

Move specified line

Specify the line number after : </ code>. For example, if you want to move to the 10th line, enter : 10 </ code>.

*** Go to document using command *** You can return to the beginning of the document, that is, the first line by executing the gg </ code> command.

*** Move to end of document using command *** You can move to the end of the document, that is, the last line by executing the G </ code> command.

Cut and paste characters

Run in command mode.

x Delete one character
dd Delete one line
yy 1 line copy
nyy n line copy
p Paste on the next or next line of the cursor character
P Paste on the line before or before the cursor character
u Cancel cut and paste once (undo)

Row cut and paste

To copy multiple lines, specify the number of lines you want to copy yy </ code>.

If you make a mistake in editing the text and undo it, enter the u </ code> command.

Replace and search

It is extremely difficult to reach the target position by using only the cursor movement and page movement commands for a huge file that does not grasp the whole picture. You can quickly move to the desired one by using the command to search for a character string in a text file. You can also use the replace command to quickly find a character string in a sentence and replace it with another character string.

/Search character string Search for character string
n Re-search downward
N Search upward again
:Target line s/Search string/Replacement string/Option Replace character string

#Replacement options
:ns/old/new Replace the first old on the nth line with new and finish
:ns/old/new/g Replace all old on the nth line with new and finish
:%s/old/new/g Replace the search term for the entire file
:%s/old/new/gc Ask for confirmation every time it is replaced
  • If g </ code> is not specified, it will be replaced only once per line.

Groups and users

A user account is required to use Linux. You can use Linux by logging in as any user. This is because the logged-in user has the authority to use the system called Linux. You can use groups to bundle multiple users. By properly setting groups and users, it is possible to give permissions to view / edit and execute files and directories, arbitrary programs and shell scripts only to the necessary users. Since the command to create / change / delete groups and users is an administrative command, it must be executed by the administrator root user </ code>.

Create user

$useradd username

#option
-c comment
//Specify a comment (character string).

-g group name
//Specify the primary group name.

-G group name
//Specify an auxiliary group.

-d
//Specify your home directory.

-s
//Specify the shell.

-u user ID number
//Specify the user ID number.

Change user account

$usermod username

#option
-c comment
//Change the comment (character string).

-g group name
//Change the primary group name.

-G group name
//Change auxiliary group.

-l Username
//Change existing username.

-u user ID number
//Change user ID number.

Delete user

$userdel username

#option
-r
//Delete home directory.

Creating a group

Use groups to handle the privileges of multiple users at once. The user always belongs to one or more groups, and the group to which the user mainly belongs is called a primary group. In addition to the groups provided from the beginning, the system administrator can define groups as needed.

$groupadd username

#option
-g Group ID number
//Specify the group ID number.

Change group registration information

$ groupmod [-g gid] [-n new-group-name]Group to be changed

#option
-n
//Specify when changing the existing group name.

-g
//Change the existing group ID. Group IDs less than 100 cannot be specified because they are used by the system.

Delete group

groupdel group name

Available users and groups

Linux provides users and groups to which they belong so that they can use the system immediately after installation. You can add multiple users and groups as needed.

General users and groups

You need an account to log in to Linux. When an account is created, a group with the same name as the user name is created, and the user is registered in the system if he / she belongs to the user group. Groups are for grouping multiple users. Individual users can be grouped by department or other unit. By using groups, you can set access rights for directories on the system and create directories that can only be accessed by users who belong to a specific group, or only users who belong to a specific group can become root users. Operation becomes possible.

root user

The root user is a special user who can change system settings, install and delete programs, and create and delete users without any restrictions. The root user is different from general users in that it can access all users' directories and read / write contents regardless of their access rights. If you can log in as the root user in this way, you can perform all operations, so you need to strictly manage the root user account.

su command

The su command is a command that allows a user who is already logged in as another user to temporarily become another user. When executing the su command, if you do not specify a user as an option, start the shell as the root user. If you execute the su command without any options, log in as the root user without changing the current directory. To change the current directory to root's home directory and log in, execute "su-" or "su --root" to change the current directory and then log in as the root user. If you log in as the root user, you can execute commands for system administration. If you manage a Linux system with multiple people, if you log in directly as the root user and work, only the history as the root user will remain, and the history of who did what will not remain. If you switch from a general user to a root user, you can immediately see when you started working as the root user. From the viewpoint of safety and management, it is desirable to log in as a general user, acquire the authority of the root user, and work on the system.

su
su - [User]

#option
su -(Or su- root)
//Can be the root user.

su - user
//Can be the specified user.

Sudo command to execute command as root user

You can use the sudo command to execute commands with superuser (root) privileges. By executing commands using sudo as needed, which cannot be done with user privileges during normal work, it is possible to execute settings and programs that require root privileges without switching the user to root with the su command. .. If you execute the sudo command with the -u option, the command will be executed by any user. If you execute the sudo command without any options, you can execute the command with root privileges. The sudo command cannot be used with the default settings on CentOS. To use the sudo command, you need to register the user in a group called the wheel group, which has superuser (root) privileges. The sudo settings make the sudo command available to users by editing the / etc / sudoers file. The / etc / sudoers file can be edited by executing the vicudo command.

sudo command
//Execute commands with superuser (root) privileges

#option
-u user
//Execute the command as the specified user.

User rights and access rights

The user ID and group ID of the file creator are the owner and owning group of the file. Owner and owning group are important attributes for file information. The owner can be changed with the chown command, and the owning group can be changed with the chgrp command.

Change of ownership

Use the chown command to change the owner of a file.

chown user[.group]directory
chown user[.group]File

#option
-R
//Target directories. Recursively change directories and files in a directory.
  • You need to be the root user to change users and groups. Directories and files can be changed without distinction. You can also use: to separate users and groups.

Change owning group

chgrp group directory
chgrp group file

#option
-Target the R directory. Recursively change directories and files in a directory.

Access that can be set to the file

The permissions of a file can be set at three levels: the user who owns the file, the user who excludes the file owner from the file ownership group, and other users. The file has three permissions: read, write, and execute for each of the three user-divided levels. Use the chmod command to change the file mode.

#Example: d rwx rwx rwx

d  rwx       rwx         rwx
Owned user Owned group Other

#meaning
r Read
w Write
x Execute or move directory

rwx can be specified for users, groups and the other three. If r is displayed, the file can be read, and if w is displayed, the file can be written. If x is displayed, the file can be executed as a program, or if it is a directory, it can be moved to a directory.

Change of access rights

chmod mode[,mode]...directory
chmod mode[,mode]...File
chmod octadecimal mode directory
chmod octadecimal mode file

#option
-Target the R directory. Recursively change a directory inside a directory (if there is a directory inside the directory, follow all the directories inside).

Set the file mode for owning users, owning groups, and other users. There are two ways to write the mode specification.

  1. Write multiple mode formats and specify them separated by commas. Specify the level of each user with 2 or 8 decimal digits.

User group and others Permission r w x r w x r w x Eighth number 4 2 1 4 2 1 4 2 1 Set value Total value Total value Total value

The mode can be set to r (read), w (write), x (execute or change directory) for u (owning user), g (owning group), o (other users), etc. Add (+) or cancel (-). To specify the same authority for u, g, and o, specify a.

File creation mode

When a new file is created, the file is created with permissions such as 644 or 644, which are the permissions specified for each user. You can use the umask command to control the creation of files with the specified permissions.

umask [8th mode mask value]

Shell script

Commands entered by the shell are in a format that can be executed sequentially by the shell script. By applying it, it is possible to automate the work by command input.

Shells and shell scripts

shell Shell means shell. When operating the functions provided by the kernel, it is necessary to operate interactively with the OS. The shell has its name because it wraps the OS, especially the kernel part, and provides interactive functionality. The shell is responsible for accepting command input, executing the command, and returning the result to the input user.

*** Shell script *** Consider the flow of compressing the / etc directory and / home directory and copying them to an external server.

# tar cvzf 120626-etc.tar.gz /etc
# tar cvzf 120626-home.tar.gz /home
# scp 120626-etc.tar.gz [email protected] ~/backup
# scp 120626-home.tar.gz [email protected] ~/backup

It's a hassle to enter this every time you run it. As a means for automating such repetitive processing, there is a method of writing a shell script and executing it. Create a file named system-backup.sh, write it, and execute system-backup.sh to execute the commands written in the file in order.

#!/bin/bash

Creating a shell script

The shell script is written in text.

$ vi lsdate.sh

Write the following script on vi and save it.

#!/bin/bash
ls
date

・ Shell designation I wrote #! / Bin / bash on the first line. The first line of the file describes the type of shell to be used and its command position. Enter the commands to be executed on the second and subsequent lines line by line.

・ Change permissions To execute the created shell script, you need to change the permissions to give the file execute permission. Check the file access authority with the ls command.

$ ls -l sdate.sh
-rw-rw-r--. 1 tooyama tooyama 

Use the chmod command to grant execute permission.

$ chmod u+x lsdate.sh
$ ls -l lsdate.sh
-rwxrw-r--. 1 tooyama tooyama

The ownership is now given execute permission. If you give execute permission to the shell script, execute it immediately.

$ ./lsdate.sh

./ is a path specification. (Run lsdate.sh in the current directory) When executing ls or cp, it is not necessary to specify such a path because it is in the path. This time, I specified the path to execute a specific shell script in the current directory. You can see that the ls command and the date command described in lsdate.sh were executed in order.

comment

A comment is a comment written on the program. In the case of the shell, the line starting with # is recognized as a comment, and the comment is ignored when the program is executed. Comments are often used to describe what a program written by a programmer does, or to temporarily disable (comment out) a specific process.

$ vi lsdate.sh
#!/bin/bash
ls
#date

Run shell script

$ ./lsdate.sh

You can see that the output of the date command has disappeared.

echo command

The echo command is a command that outputs the character string given as an argument to standard output.

echo [option]String

#option
-n
//Suppress line breaks. Normal output is broken, but with this option it is not.
$ echo Message test

variable

Set the value to abc in the shell function and check the contents with the echo command.

$ abc=123
$ echo $abc
123
(Display the contents of abc)

Assign 123 to the variable abc. In bash, you can use one-dimensional array variables. Enclose the element in []. To display the contents of an array variable, enclose the array variable in {} after the $.

$ abc[0]=123
$ abc[1]=456
$ echo ${abc[0]}
123
$ index=1
$ echo ${abc[$index]}
456

*** Shell and environment variables *** There are two types of variables in the shell. Shell variables and environment variables. Shell variables are valid only inside the shell you are running. Environment variables are also valid in commands executed from them. Environment variables can be created from shell variables.

$ export abc
$ export xyz=234

The first command creates an environment variable called abc. No value is assigned to abc. The second command creates an environment variable called xyz. 234 is assigned to xyz. Next, use the two scripts BBB.sh and CCC.sh to check the difference in behavior between shell variables and environment variables.

$ cat BBB.sh
#!/bin/bash
xxx=123                  #Assign 123 to the shell variable xxx
export yyy=234           #Assign 234 to the environment variable yyy
echo xxx=$xxx in BBB.sh  #Show the value of the variable xxx
echo yyy=$yyy in BBB.sh  #Show the value of the variable yyy
./CCC.sh                 #CCC.run sh

$ cat CCC.sh
#!/bin/bash
echo xxx=$xxx in CCC.sh  #Show the value of the variable xxx
echo yyy=$yyy in CCC.sh  #Show the value of the variable yyy

$ ./BBB.sh
xxx=123 in BBB.sh
yyy=234 in BBB.sh
xxx= in CCC.sh
yyy=234 in CCC.sh

Since yyy is an environment variable, the value is displayed because it is inherited up to CCC.sh.

read command

The read command reads data from standard input. If the variable already contains data, it will be overwritten with new data.

read variable name
$ echo $abc
123

$ read abc
aaa
(Enter something)

$ echo $abc
aaa
(The contents of the shell variable abc are replaced)

Shell variables

To display a list of shell variables, use the set command. If you want to delete it, use unset.

$ set
BASH=/bin/bash
BASHOPTS=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:hostcomplete:intera
BASH_ALIASES=()
$ set | grep ^abc
abc=aaa
(Check only shell variables starting with abc)
$ unset abc
(Delete shell variable abc)
$ set | grep ^abc

Environment variable

Use the env command to display a list of current environment variables. To delete the registered environment variable, use the unset command.

$ env
ABC=999999
HOSTNAME=host1.alpha.jp
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000

$ env | grep ^ABC
ABC=999999
$ unset ABC
(Delete environment variable ABC)
$ env | grep ^ABC

Quotation marks

In shell scripts, strings may be enclosed in quotation marks. The quotes that can be used include'(single quotes), "(double quotes), and` (back quotes), and the processing of the string enclosed by the quotes used differs. If there is a variable with "" for reference in the character string enclosed in single fort, the variable is not expanded because "" is also recognized as a character string. For tabular quotes, variables with "" in quotes are expanded strings. The character string enclosed in backticks is interpreted as a command, and if there is a variable with "" at this time, the command is executed after expanding it.

$ ABC=123
$ echo 'Value of ABC is $ABC.'
Value of ABC is $ABC.
($ABC was recognized as a character and displayed as it was)
$ echo "Value of ABC is $ABC."
Value of ABC is 123.
($ABC was recognized as a variable and the content 123 was expanded)
$ XYZ=`date`;
$ echo"It is $XYZ now."
($XYZ contains the execution result of the date command)
$ echo "It is `date` now."
(Enclose the entire string in double quotes, insert the date command in backticks, omit the assignment to the variable XYZ)

argument

Shell scripts can reference options as arguments at run time. Arguments can be referred to by specifying the argument number after $ such as $ 1, $ 2, etc.

$ cat args.sh
#!/bin/bash

echo '$1:' $1;
echo '$2:' $2;
echo '$3:' $3;
echo '$0:' $0;
echo '$#:' $#;
$ ./args.sh aaa bbb ccc
$1: aaa
$2: bbb
$3: ccc
$0: ./args.sh
$#: 3
($1-$3 is the argument,$0 is the execution command name,$#Indicates the number of arguments)

shift statement

The shift command shifts the order of the arguments. When shift is executed, $ 2 becomes $ 1, $ 3 becomes $ 2, and so on.

$ cat argsshift.sh
#!/bin/bash

echo '$1:' $1;
echo '$2:' $2;
echo '$3:' $3;
shift
echo '$1:' $1;
echo '$2:' $2;
$ ./argsshift.sh aaa bbb ccc
$1: aaa
$2: bbb
$3: ccc
$1: bbb
($1 changed to bbb)
$2: ccc
($2 changed to ccc)

Escape sequence

Some programming languages have special treatment. For example, how to output "(double quotes) like" Value of ABC is "123". "With the echo command.

$ ABC=123
$ echo "Value of ABC is "$ABC"."
Value of ABC is 123.
($ABC""I surrounded it with""Is not displayed)
$ echo "Value of ABC is ¥"$ABC¥"."
Value of ABC is "123".
(I want to display"By adding "¥" just before"Can be displayed.

In this way, in shell scripts, \ (backslash) is called an escape character, and a special character changes the treatment of the immediately following character. Effective when you want to change the handling of characters in combination with the quotation marks used. \ (Backslash) is also valid for line feed code. By adding \ (backslash) at the end of the line, it can be wrapped in the middle of the character string. The visibility of commands can be improved by inserting line breaks appropriately.

$ echo "I am a cat. As yet I have no name."
I am a cat. As yet I have no name.
$ echo "I am a cat.¥
> As yet I have no name."
I am a cat. As yet I have no name.

Backslash line breaks can also be used in shell scripts. The backslash is originally , but in many Japanese environments it is displayed as .

$ vi escape.sh

#!/bin/bash

echo "I am a cat. ¥
As yet I have no name."

$ ./escape.sh
I am a cat. As yet I have no name.

\ (Backslash) has other uses, and there is a method called escape sequence, which is a character string that has a special meaning as a set with the following one character. Commonly used ones are \ t (tab), \ n (line feed), and \ ooo (o is a number in octal notation).

$ echo -e "I am a cat. ¥nAs yet I have no name¥041"
I am a cat.
As yet I have to name!

source command

Set up a shell environment by reading the specified file with a shell internal command such as bash. The contents of the file are interpreted as shell commands and executed. A common use is to change the shell environment settings such as ".bashrc" and ".bash_profile" and then enable the settings on the current shell without logging back in.

$ cat set.sh
(set.Check the contents of sh)

#!/bin/bash
abc=xyz
echo $abc
$ echo $abc
($Nothing is displayed because abc does not store anything)
$ ./set.sh
xyz
(The value of the variable abc set in the script was output by echo)
$ echo $abc
(The value setting for the variable abc is valid only in the script, so nothing is displayed)
$ source set.sh
xyz
(The value of the variable abc set in the script was output by echo)
$ echo $abc
xyz

Conditional branch

if conditional expression 1 then...elif conditional expression 2... else ... fi

#Operators for numerical comparison
a -True if eq b a and b are equal to
a -true if ne b a and b are not equal (not equal to)
a -True if ge b a is greater than or equal to
a -True if le b a and less than b (less than or equal to)
a -True if gt b a is greater than b
a -True if lt b a is less than b

Check file attributes

if test -d path; then ...

The -d part corresponds to the file attribute confirmation operator. Since -d determines whether it is a dict, the entire if statement is a conditional expression that returns the true value if the path appears in the directory. The file attribute confirmation operators are as follows.

-f File name True for regular files
-d Filename True if directory
-e Filename True if the file exists
-L File name True if symbolic
-r File name True if readable file
-w File name True if readable file
-x Filename True if the file exists and has execute permission
-s Filename True if size is greater than 0

The test command can also be written using [].

if [Conditional clause] ; then ...
if test conditional clause; then ...

There are other comparison operators for files besides attributes. For details, refer to the test command item with the man command.

man test

Overlap multiple conditions

Logical AND

[Condition A-a Condition B-a Condition C] ...
[Condition A] && [Condition B] && [Condition C] ...

Note that -a and && are used differently depending on whether they are inside or outside [].

*** OR ***

[Condition A-o Condition B-o Condition C] ...
[Condition A] || [Condition B] || [Condition C] ...

One-to-many conditional branch

if conditional expression then
elif conditional expression then
elif conditional expression then
fi

In the shell script, a case statement is prepared so that one-to-many branches can be described.

case variable in
Value A)
Process 1;;
Value B)
Process 2;;
esac

When the value of the variable is the value A, the process 1 is executed. It is important that the end ends with esac, which is a description from the reverse of the case statement. Multiple values can be specified by separating them with a pipe symbol (|).

$ cat case.sh
#!/bin/bash

case $1 in
        a|A)
           echo "A or A was entered as an argument";;
        b|B)
           echo "B or B was entered as an argument";;
esac

When you do this

$ ./case.sh a
A or A was entered as an argument
$ ./case.sh B
B or B was entered as an argument

An asterisk (*) is used as the value to describe the processing when no value is matched.

$ cat defaultcase.sh
#!/bin/bash

case $1 in
        1)
           echo "1 was entered as an argument";;
        2)
           echo "2 was entered as an argument";;
        *)
           echo "1,Anything other than 2 was entered";;
esac

When you do this

$ ./defaultcase.sh 1
1 was entered as an argument
$ ./defaultcase.sh 2
2 was entered as an argument
$ ./defaultcase.sh 0
1,Entered other than 2

Recommended Posts