1. Execute multiple commands in one line
When executing multiple commands on one command line, separate the commands with semicolons.
$ date ; who
Mon Sep 24 19:44:35 EST 2007
rich :0 2007-09-24 18:23 (console)
rich pts/1 2007-09-24 18:24
rich pts/0 2007-09-24 18:42
barbara pts/2 2007-09-24 19:30
katie pts/3 2007-09-24 19:39
$
2. Write the script file
When writing a script file, always define the shell to be used in the first line as follows.
$ touch test1
$gedit test1
#! /bin/bash
# this is test script file ==> #The following characters are commented out.
date
who
$
When I run the script after writing the above, it says that the command cannot be found as shown below.
$ test1
bash: test1: command not found
$
In this case, add the path where the current script file is located to the PATH variable used by the current shell. Alternatively, you must indicate the location of the file using an absolute or relative path. If the current path is added to the PATH variable and then the corresponding script file is executed, the message "Permission denied" appears as shown below.
$ ./test1 bash: ./test1: deny permission
Then, add execution permission to the owner and run it.
$ chmod u+x test1
$ ./test1
Mon Sep 24 19:58:35 EST 2007
rich :0 2007-09-24 18:23 (console)
rich pts/1 2007-09-24 18:24
rich pts/0 2007-09-24 18:42
barbara pts/2 2007-09-24 19:30
katie pts/3 2007-09-24 19:39
$
This time, we will use the echo command in the script file to display a message when the script is executed. First of all, if you want to output a sentence when executing a script, you can just use the echo command, but if a special symbol is included in the sentence, you need to enclose the sentence in single quotation marks or double quotation marks to display it as desired. Let's take a look at the example below. Let's edit the test1 file as below and run it.
$gedit test1
#! /bin/bash
echo "let's check date"
date
echo "Shows who has logged in"
who
#
$ ./test1
let's check date
2021. 05. 30. (Sun) 20:00:38 KST
Shows who has logged in
hyowon tty7 2021-05-29 10:36 (:0)
$
So, how can I display the output of the command on one line after the echo command? You can do this with the -n option. Then, modify the script as follows.
$gedit test1
#! /bin/bash
echo -n "let's check date"
date
echo "Shows who has logged in"
who
#
When the script is executed, the output result of the command appears on one line as shown below.
$ ./test1
let's check date2021. 05. 30. (Sun) 20:06:13 KST
Shows who has logged in
hyowon tty7 2021-05-29 10:36 (:0)
$
3. Using Variables
In the script, you can write a script using environment variables used in Linux. First, if you want to see the currently active variables, use the set command as shown below to output the currently used environment variables.
hyowon@hyowon-800G5M-800G5W:~$ set
BASH=/bin/bash
BASHOPTS=checkwinsize:cmdhist:complete_fullquote:expand_aliases:extglob:extquote:force_fignore:histappend:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
BASH_COMPLETION_COMPAT_DIR=/etc/bash_completion.d
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="4" [1]="3" [2]="48" [3]="1" [4]="release" [5]="x86_64-pc-linux-gnu")
BASH_VERSION='4.3.48(1)-release'
CLUTTER_IM_MODULE=xim
COLUMNS=80
COMPIZ_BIN_PATH=/usr/bin/
COMPIZ_CONFIG_PROFILE=ubuntu
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-bfMwnwWEoh
DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path
DESKTOP_SESSION=ubuntu
DIRSTACK=()
DISPLAY=:0
EUID=1000
GDMSESSION=ubuntu
GDM_LANG=ko
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
GNOME_KEYRING_CONTROL=
GNOME_KEYRING_PID=
GPG_AGENT_INFO=/home/hyowon/.gnupg/S.gpg-agent:0:1
GROUPS=()
GTK2_MODULES=overlay-scrollbar
GTK_IM_MODULE=fcitx
GTK_MODULES=gail:atk-bridge:unity-gtk-module
HISTCONTROL=ignoreboth
HISTFILE=/home/hyowon/.bash_history
HISTFILESIZE=2000
HISTSIZE=1000
HOME=/home/hyowon
HOSTNAME=hyowon-800G5M-800G5W
HOSTTYPE=x86_64
IFS=$' \t\n'
IM_CONFIG_PHASE=1
INSTANCE=
JOB=unity-settings-daemon
LANG=ko_KR.UTF-8
LANGUAGE=ko
LESSCLOSE='/usr/bin/lesspipe %s %s'
LESSOPEN='| /usr/bin/lesspipe %s'
LINES=24
LOGNAME=hyowon
|
There are too many variables, so only a few are shown. So let's write a script using some of the above variables.
$gedit test1
#! /bin/bash
echo -n "let's check date"
date
echo "Shows who has logged in"
who
echo "Logged in user is: $USER"
echo "User ID is: $UID:"
echo "The user's HOME directory is: $HOME"
#
Let's run this script
$ ./test1
let's check date 2021. 05. 30. (Sun) 20:20:01 KST
Shows who has logged in
hyowon tty7 2021-05-29 10:36 (:0)
The logged in user is: hyowon
User ID is: 1000:
The user's HOME directory is: /home/hyowon
$
Using User Variables
In Linux, you can declare any variables you need. Variables can be created using letters and numbers or underscore (_) up to 20 characters. User variables are case-sensitive. So Value1 and VALUE1 are different variables. Unlike programming languages, when declaring a variable, there is no need to declare a Type. For an example of creating a variable, see below.
var1=10
var2=-57
var3=testing
var4="still more testing" ==> When saving a string, enclose the sentence in double or single quotation marks.
$touch test3
$gedit test3
#! /bin/bash
#Testing variables.
days=5
guest="katie"
echo "$guest checked in $days days ago"
guest="Jessica"
echo "$guest checked in $days days ago"
#
As you can see in the script above, when you use a variable, you must always use it as '$variable name'. And if you want to treat the $ as a character, add a backslash in front of the $ like \$, and the $ will be treated as a character.
So let's try running it to see if it works.
$ chmod u+x test3 ==> Give the owner execute permission.
$ ./test3
katie
checked in 5 days ago
Jessica checked in 5 days ago
Using Backticks
If you want to execute a Linux command in a script and save the result in a variable, you can save the command execution result in a variable by using a backtick (`) to enclose the command.
$touch test4
$gedit test4
#! /bin/bash
#Example of backtick
testing=`date`
echo "the date and time are:" $testing
#
Then give the user execute permission and run it.
$chmod u+x test4
$./test4
the date and time are: 2021. 06. 01. (화) 17:37:11 KST
As an example, let's create an example that saves the command execution result and specifies the file name as the date.
#! /bin/bash
# Output the files under /usr/bin and create a log file with the date name
today=`date +%y%m%d' ==> Creates a date format with 2 digits each year/month/day and
stores it in the today variable.
ls /usr/bin -al > log.$today ==> The ls command prints a list of files and redirects them to the log.date file.
#
Then let's see the execution result.
$ ./test5
$ ls -al log.*
-rw-rw-r-- 1 hyowon hyowon 144842 Jun 1 17:47 log.210601
4. I/O redirect
Putting the command output result as an input to a file or other script other than the monitor. Linux provides an operator that can change the direction of input/output. Let's study them one by one.
output redirect
When saving the command output result to a file, the syntax is as follows.
command > outputfile
A single angle > is used to create a new file, and >> is used to add additional content to an existing file. Then, for example, to save the execution result of the date command in the test6 file, enter the command as follows. It's possible.
$ date > test6
$ ls -l t*
-rw-rw-r-- 1 root root 10 5월 29 14:12 test.txt
-rwxrw-r-- 1 hyowon hyowon 229 5월 30 20:19 test1
-rw-rw-r-- 1 hyowon hyowon 0 4월 7 17:51 test12.sh
-rwxrw-r-- 1 hyowon hyowon 157 6월 1 17:21 test3
-rwxrw-r-- 1 hyowon hyowon 91 6월 1 17:37 test4
-rwxrw-r-- 1 hyowon hyowon 151 6월 1 17:47 test5
-rw-rw-r-- 1 hyowon hyowon 33 6월 1 18:11 test6
$ cat test6
2021. 06. 01. (Tue) 18:11:24 KST
Now, let's add the who command result to the test6 file.
$who >> test6
$ cat test6
2021. 06. 01. (Tue) 18:11:24 KST
hyowon tty7 2021-05-29 10:36 (:0)
input redirect
In contrast to output redirection, input redirection is used to insert a file as input to a command. How to use is as follows.
command < inputfile
Let's try input redirection using the wc command. First, the wc command displays how many lines, how many words, and how many bytes in a file.
$ wc < test6
2 11 77
inline input redirect
Inline input redirects require the use of << symbols, followed by << followed by text that marks the end of the input. This method is used when there are several data to be input in one command, and the usage format is command << marker (command end character). Let's do a simple test using wc.
hyowon@hyowon-800G5M-800G5W:~$ wc << END
> test string 1
> test string 2
> test string 3
> END
3 9 42
When the END word is encountered, the command ends and the result is 3 lines, 9 words. It prints 42 bytes.
5. PIPE instruction
Pipe commands are used to pass the output of one command to the input of another command. How to command | You can use it in command format.
For example, to output the contents of /etc/passwd in alphabetical order, you can use it as follows.
$ cat /etc/paswd | sort
_apt:x:105:65534::/nonexistent:/bin/false
avahi-autoipd:x:110:119:Avahi autoip daemon,,,:/var/lib/avahi-autoipd:/bin/false
avahi:x:111:120:Avahi mDNS daemon,,,:/var/run/avahi-daemon:/bin/false
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
colord:x:113:123:colord colour management daemon,,,:/var/lib/colord:/bin/false
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
dnsmasq:x:112:65534:dnsmasq,,,:/var/lib/misc:/bin/false
games:x:5:60:games:/usr/games:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
guest-3moqme:x:997:997:손님:/tmp/guest-3moqme:/bin/bash
If you want to save the output result to a file here, you can use an output redirect as follows.
$cat /etc/passwd | sort > passwd.txt
6. Math Operations
Using the expr command There are two ways to perform mathematical operations in the Linux shell. One is to use the expr command, and the other is to use brackets. First, let's look at how to use the expr command. How to use is simple It is used in the form of 'expr numeric operator number'. However, to use * or other operators with other meanings, you must add a backslash in front of them.
~$ expr 5 + 3
8
$ expr 5 - 3
2
$ expr 5 * 2
expr: Syntax error
$ expr 5 \* 2
10
Expr can also be used for logical operations, please refer to the table below.
So let's try it in a script.
$touch test7
#! /bin/bash
# Using the expr command script
var1=10
var2=20
var3=`expr $var2 / $var1`
echo The result is $var3
#
So let's run it.
$./test7
The result is 2
The result seems to be normal.. But the expr command is
using a bracket
A way to perform mathematical operations other than the expr command is to use brackets. The usage format is as follows. This is a method to put a $ sign in front of a bracket to convert the result value in the bracket to a variable and save it.
$ var1=$[1 + 5]
So let's try it in a script
$touch test8
$chmod u+x test8
#! /bin/bash
var1=50
var2=30
var=20
var4=$[var1 * ($var2 - $var3)]
echo the result is $var4
#
Then let's run it.
$ ./test8
the result is 500
floating point
arithmetic In Linux, even if expr or brackets are used, there is a limitation that floating-point operations cannot be processed. To use it, bc (bash caculate) is used for calculations. So let's see how to use it from the command line first.
$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
4 * 5
20
4.1 * 10.1
41.4
3.342 * (3 + 5)
26.736
quit
$
You can set how many decimal places to display the result of bc operation. This method is to designate the scale variable value as shown below. Let's look at an example below.
$ bc -q (-q is the option to delete the welcome banner)
3.44 / 5
0
scale=4
3.44 / 5
.6880
quit
$
So let's use bc in our script. First of all, here's how to use it:
variable=`echo "options; expression" | bc`
You can wrap the whole with a backtick and define a variable in the option part. So, let's run it with an example.
$touch test8
#! /bin/bash
var1=20
var2=3.14159
var3=`echo "scale=4; $var1 * $var2" | bc`
var4=`echo "scale=4; $var3 * $var2" | bc`
echo The result is $var4
#
If you run
$ ./test9
The result is 197.39175
When there are several equations, it is a little more convenient to use the following as an inline redirect.
#! /bin/bash
var1=10.46
var2=43.67
var3=33.2
var4=71
var5=`bc << EOF
scale = 4
a1 = ( $var1 * $var2)
b1 = ($var3 * $var4)
a1 + b1
EOF
`
echo The final answer for this mess is $var5
#
$ ./test10
The final answer for this mess is 2813.9882
$
Using exit codes
In Linux, the execution result of the command is stored as a number in the exit variable. The agreed exit code is as shown in the table below, and the script uses this exit code to create a script that performs various operations, so it is used in many scripts. If the command is executed successfully, exit code returns 0, and when no command is executed, exit code returns to number 127. You can check this code value by using echo $?.
$ date
Sat Sep 29 10:01:30 EDT 2007
$ echo $?
0
$
$ asdfg
-bash: asdfg: command not found
$ echo $?
127
$
In the script, you can also save the exit code value as a user-desired value. Let's look at the example below. In this case, you can specify the return value after the exit command.
$touch test11
#!/bin/bash
# testing the exit status
var1=10
var2=30
var3=$[ $var1 * var2 ]
echo The value is $var3
exit $var3
$
$ ./test11
The value is 300
$ echo $?
44
$
The reason why the exit code is 44 here is that when the shell script exceeds the exit code range (0 to 255), the remainder divided by 256 is returned as the exit code.
'Shell Script' 카테고리의 다른 글
8 Detailed Structed Shell Command (1) | 2022.08.12 |
---|---|
7 Structured Command (5) | 2022.08.11 |
5 Linux File Permission (2) | 2022.08.11 |
4 Environment variables (1) | 2022.08.11 |
3 Bash Shell Command (8) | 2022.08.10 |