สร้าง directory ชื่อ log
#!/bin/bash dir=log if [ ! -d $dir ] then mkdir $dir echo "create directory $dir" else echo "Directory exists" fi
สร้าง directory ชื่อ log
#!/bin/bash dir=log if [ ! -d $dir ] then mkdir $dir echo "create directory $dir" else echo "Directory exists" fi
$ date --help Usage: date [OPTION]... [+FORMAT] or: date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] Display the current time in the given FORMAT, or set the system date. Mandatory arguments to long options are mandatory for short options too. -d, --date=STRING display time described by STRING, not 'now' -f, --file=DATEFILE like --date once for each line of DATEFILE -I[TIMESPEC], --iso-8601[=TIMESPEC] output date/time in ISO 8601 format. TIMESPEC='date' for date only (the default), 'hours', 'minutes', 'seconds', or 'ns' for date and time to the indicated precision. -r, --reference=FILE display the last modification time of FILE -R, --rfc-2822 output date and time in RFC 2822 format. Example: Mon, 07 Aug 2006 12:34:56 -0600 --rfc-3339=TIMESPEC output date and time in RFC 3339 format. TIMESPEC='date', 'seconds', or 'ns' for date and time to the indicated precision. Date and time components are separated by a single space: 2006-08-07 12:34:56-06:00 -s, --set=STRING set time described by STRING -u, --utc, --universal print or set Coordinated Universal Time (UTC) --help display this help and exit --version output version information and exit FORMAT controls the output. Interpreted sequences are: %% a literal % %a locale's abbreviated weekday name (e.g., Sun) %A locale's full weekday name (e.g., Sunday) %b locale's abbreviated month name (e.g., Jan) %B locale's full month name (e.g., January) %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005) %C century; like %Y, except omit last two digits (e.g., 20) %d day of month (e.g., 01) %D date; same as %m/%d/%y %e day of month, space padded; same as %_d %F full date; same as %Y-%m-%d %g last two digits of year of ISO week number (see %G) %G year of ISO week number (see %V); normally useful only with %V %h same as %b %H hour (00..23) %I hour (01..12) %j day of year (001..366) %k hour, space padded ( 0..23); same as %_H %l hour, space padded ( 1..12); same as %_I %m month (01..12) %M minute (00..59) %n a newline %N nanoseconds (000000000..999999999) %p locale's equivalent of either AM or PM; blank if not known %P like %p, but lower case %r locale's 12-hour clock time (e.g., 11:11:04 PM) %R 24-hour hour and minute; same as %H:%M %s seconds since 1970-01-01 00:00:00 UTC %S second (00..60) %t a tab %T time; same as %H:%M:%S %u day of week (1..7); 1 is Monday %U week number of year, with Sunday as first day of week (00..53) %V ISO week number, with Monday as first day of week (01..53) %w day of week (0..6); 0 is Sunday %W week number of year, with Monday as first day of week (00..53) %x locale's date representation (e.g., 12/31/99) %X locale's time representation (e.g., 23:13:48) %y last two digits of year (00..99) %Y year %z +hhmm numeric time zone (e.g., -0400) %:z +hh:mm numeric time zone (e.g., -04:00) %::z +hh:mm:ss numeric time zone (e.g., -04:00:00) %:::z numeric time zone with : to necessary precision (e.g., -04, +05:30) %Z alphabetic time zone abbreviation (e.g., EDT) By default, date pads numeric fields with zeroes. The following optional flags may follow '%': - (hyphen) do not pad the field _ (underscore) pad with spaces 0 (zero) pad with zeros ^ use upper case if possible # use opposite case if possible After any flags comes an optional field width, as a decimal number; then an optional modifier, which is either E to use the locale's alternate representations if available, or O to use the locale's alternate numeric symbols if available. Examples: Convert seconds since the epoch (1970-01-01 UTC) to a date $ date --date='@2147483647' Show the time on the west coast of the US (use tzselect(1) to find TZ) $ TZ='America/Los_Angeles' date Show the local time for 9AM next Friday on the west coast of the US $ date --date='TZ="America/Los_Angeles" 09:00 next Fri' GNU coreutils online help: <http://www.gnu.org/software/coreutils/> For complete documentation, run: info coreutils 'date invocation'
$ date --version date (GNU coreutils) 8.22 Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Written by David MacKenzie.
ตัวอย่าง
Open a terminal application and type the following command:
$ date Tue Feb 7 15:23:13 +07 2023
format the date
$ date +"%y-%m-%d" 23-02-07 $ date +"%Y-%m-%d" 2023-02-07
Simply display the current time on Linux:
]$ date "+%T" 15:24:15
To print the date of the day before yesterday, run:
$ date --date='2 days ago' Sun Feb 5 15:25:37 +07 2023
Want to see the day of year of Christmas in the current year? Try:
$ date --date='25 Dec' +%j 359
Display the current full month name and the day of the month:
$ date '+%B %d' February 07
It is easy to see the syntax of a function and believe you know how to use it. But it is always a better choice to understand a function through examples because they help you understand the role that different aspects of a function play.
Here are some useful examples of if-else in shell scripts to give you a better idea of how to use this tool.
Command | Description |
---|---|
&& | Logical AND |
$0 | Argument 0 i.e. the command that’s used to run the script |
$1 | First argument (change number to access further arguments) |
-eq | Equality check |
-ne | Inequality check |
-lt | Less Than |
-le | Less Than or Equal |
-gt | Greater Than |
-ge | Greater Than or Equal |
When trying to understand the working of a function like if-else in a shell script, it is good to start things simple. Here, we initialize two variables a and b, then use the if-else function to check if the two variables are equal. The bash script should look as follows for this task.
#!/bin/bash m=1 n=2 if [ $n -eq $m ] then echo "Both variables are the same" else echo "Both variables are different" fi
Output:
Both variables are different
The more common use of if-else in shell scripts is for comparing two values. Comparing a variable against another variable or a fixed value helps is used in a variety of cases by all sorts of programmers.
For the sake of this example, we will be initializing two variables and using the if-else function to find the variable which is greater than the other.
#!/bin/bash a=2 b=7 if [ $a -ge $b ] then echo "The variable 'a' is greater than the variable 'b'." else echo "The variable 'b' is greater than the variable 'a'." fi
Output:
The variable 'b' is greater than the variable 'a'.
Sometimes we come across situations where we need to deal with and differentiate between even and odd numbers. This can be done with if-else in shell scripts if we take the help of the modulus operator.
The modulus operator divides a number with a divisor and returns the remainder.
As we know all even numbers are a multiple of 2, we can use the following shell script to check for us whether a number is even or odd.
#!/bin/bash n=10 if [ $((n%2))==0 ] then echo "The number is even." else echo "The number is odd." fi
Output:
The number is even
As you can see, we’ve enclosed a part of the condition within double brackets. That’s because we need the modulus operation to be performed before the condition is checked.
Also, enclosing in double brackets runs statements in C-style allowing you to process some C-style commands within bash scripts.
The if-else function is known for its versatility and range of application. In this example, we will use if-else in shell script to make the interface for a password prompt.
To do this, we will ask the user to enter the password and store it in the variable pass.
If it matches the pre-defined password, which is ‘password’ in this example, the user will get the output as -“The password is correct”.
Else, the shell script will tell the user that the password was incorrect and ask them to try again.
#!/bin/bash echo "Enter password" read pass if [ $pass="password" ] then echo "The password is correct." else echo "The password is incorrect, try again." fi
#!/bin/bash a=NUM_FILE=`find . -type f -print | wc -l` b=4 if [ $a -eq $b ] then echo "Exactly the same." else echo "Wrong number" fi
ถ้า process ไม่ได้รันอยู่ ให้ start process
#!/bin/bash a=`ps -ef | grep PROCESS_NAME | wc -l` b=1 if [ $a -gt $b ] then echo "Found existing process" else echo "Not found existing, START PROCESS_NAME" start.sh fi
ถ้า process รันอยู่ ให้ stop process
#!/bin/bash a=`ps -ef | grep PROCESS_NAME | wc -l` b=1 if [ $a -gt $b ] then echo "Found existing, STOP PROCESS_NAME " stop.sh else echo "Process not found" fi
ทดสอบบน Red Hat 7.7
The pgrep command allows a user to find process IDs in the running program in the system’s current state.
$ pgrep --version pgrep from procps-ng 3.3.10
$ pgrep --help Usage: pgrep [options] <pattern> Options: -d, --delimiter <string> specify output delimiter -l, --list-name list PID and process name -a, --list-full list PID and full command line -v, --inverse negates the matching -w, --lightweight list all TID -c, --count count of matching processes -f, --full use full process name to match -g, --pgroup <PGID,...> match listed process group IDs -G, --group <GID,...> match real group IDs -n, --newest select most recently started -o, --oldest select least recently started -P, --parent <PPID,...> match only child processes of the given parent -s, --session <SID,...> match session IDs -t, --terminal <tty,...> match by controlling terminal -u, --euid <ID,...> match by effective IDs -U, --uid <ID,...> match by real IDs -x, --exact match exactly with the command name -F, --pidfile <file> read PIDs from file -L, --logpidfile fail if PID file is not locked --ns <PID> match the processes that belong to the same namespace as <pid> --nslist <ns,...> list which namespaces will be considered for the --ns option. Available namespaces: ipc, mnt, net, pid, user, uts -h, --help display this help and exit -V, --version output version information and exit For more details see pgrep(1).
ตัวอย่าง
หา process ID ของ nginx
$ pgrep nginx 1085 1086
specify output delimiter ด้วย -d
$ pgrep -d: nginx 1085:1086
match exactly with the command name ด้วย -x
$ pgrep -x nginx 1085 1086
หา process ID จาก user name
$ pgrep -u jack
You can check the sudo configuration file syntax using the visudo command, which supports a --check
or -c
command line option to only validate a file without an edit. The -f
option displays the error message and opens the file for editing:
$ sudo visudo -c /etc/sudoers: parsed OK /etc/sudoers.d/README: parsed OK
$ visudo -h visudo - safely edit the sudoers file usage: visudo [-chqsV] [[-f] sudoers ] Options: -c, --check check-only mode -f, --file=sudoers specify sudoers file location -h, --help display help message and exit -q, --quiet less verbose (quiet) syntax error messages -s, --strict strict syntax checking -V, --version display version information and exit
$ sudo visudo -V visudo version 1.8.31 visudo grammar version 46
JSON is an acronym for JavaScript Object Notation. Often used in web apps, but it is not limited to JavaScript. One can use any programming language such as Perl, Python or CLI tools such as jq.
CSV is an acronym for Comma-separated values. It is a text file you can use in spreadsheet apps, programming languages and many other apps.
Since jq is available in most common repos, I will use that one for my needs. Here is how to install jq on a Debian or Ubuntu Linux using the apt command/apt-get command:
$ sudo apt install jq
RHEL/Fedora/CentOS/Alma/Rocky Linux user try the dnf command:
$ sudo dnf install jq
Alpine Linux user try the apk command:
$ sudo apk add jq
SUSE or OpenSUSE Linux user try the zypper command:
$ sudo zypper in jq
macOS / OS X user install homebrew and then use the brew command:
$ brew install jq
help
$ jq -h jq - commandline JSON processor [version 1.6] Usage: jq [options] <jq filter> [file...] jq [options] --args <jq filter> [strings...] jq [options] --jsonargs <jq filter> [JSON_TEXTS...] jq is a tool for processing JSON inputs, applying the given filter to its JSON text inputs and producing the filter's results as JSON on standard output. The simplest filter is ., which copies jq's input to its output unmodified (except for formatting, but note that IEEE754 is used for number representation internally, with all that that implies). For more advanced filters see the jq(1) manpage ("man jq") and/or https://stedolan.github.io/jq Example: $ echo '{"foo": 0}' | jq . { "foo": 0 } Some of the options include: -c compact instead of pretty-printed output; -n use `null` as the single input value; -e set the exit status code based on the output; -s read (slurp) all inputs into an array; apply filter to it; -r output raw strings, not JSON texts; -R read raw strings, not JSON texts; -C colorize JSON; -M monochrome (don't colorize JSON); -S sort keys of objects on output; --tab use tabs for indentation; --arg a v set variable $a to value <v>; --argjson a v set variable $a to JSON value <v>; --slurpfile a f set variable $a to an array of JSON texts read from <f>; --rawfile a f set variable $a to a string consisting of the contents of <f>; --args remaining arguments are string arguments, not files; --jsonargs remaining arguments are JSON arguments, not files; -- terminates argument processing; Named arguments are also available as $ARGS.named[], while positional arguments are available as $ARGS.positional[]. See the manpage for more options.
ตัวอย่างไฟล์ df.json
[ { "fs": "/dev/mapper/vgubuntu-root", "type": "ext4", "size": "915G", "used": "135G", "avail": "734G", "usedpercentage": "16%", "mounted": "/" }, { "fs": "/dev/nvme0n1p2", "type": "ext4", "size": "1.4G", "used": "378M", "avail": "939M", "usedpercentage": "29%", "mounted": "/boot" }, { "fs": "/dev/nvme0n1p1", "type": "vfat", "size": "511M", "used": "30M", "avail": "482M", "usedpercentage": "6%", "mounted": "/boot/efi" } ]
convert JSON to CSV
$ cat df.json | jq -r '.[]| join(",")' /dev/mapper/vgubuntu-root,ext4,915G,135G,734G,16%,/ /dev/nvme0n1p2,ext4,1.4G,378M,939M,29%,/boot /dev/nvme0n1p1,vfat,511M,30M,482M,6%,/boot/efi
$ cat df.json | jq -r '.[]| join(",")' > df.csv $ cat df.csv /dev/mapper/vgubuntu-root,ext4,915G,135G,734G,16%,/ /dev/nvme0n1p2,ext4,1.4G,378M,939M,29%,/boot /dev/nvme0n1p1,vfat,511M,30M,482M,6%,/boot/efi
We use the df command to find total disk space and available space on a Linux / Unix file system.
The df is an acronym for disk free.
$ df --help Usage: df [OPTION]... [FILE]... Show information about the file system on which each FILE resides, or all file systems by default. Mandatory arguments to long options are mandatory for short options too. -a, --all include pseudo, duplicate, inaccessible file systems -B, --block-size=SIZE scale sizes by SIZE before printing them; e.g., '-BM' prints sizes in units of 1,048,576 bytes; see SIZE format below -h, --human-readable print sizes in powers of 1024 (e.g., 1023M) -H, --si print sizes in powers of 1000 (e.g., 1.1G) -i, --inodes list inode information instead of block usage -k like --block-size=1K -l, --local limit listing to local file systems --no-sync do not invoke sync before getting usage info (default) --output[=FIELD_LIST] use the output format defined by FIELD_LIST, or print all fields if FIELD_LIST is omitted. -P, --portability use the POSIX output format --sync invoke sync before getting usage info --total elide all entries insignificant to available space, and produce a grand total -t, --type=TYPE limit listing to file systems of type TYPE -T, --print-type print file system type -x, --exclude-type=TYPE limit listing to file systems not of type TYPE -v (ignored) --help display this help and exit --version output version information and exit Display values are in units of the first available SIZE from --block-size, and the DF_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000). FIELD_LIST is a comma-separated list of columns to be included. Valid field names are: 'source', 'fstype', 'itotal', 'iused', 'iavail', 'ipcent', 'size', 'used', 'avail', 'pcent', 'file' and 'target' (see info page). GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report df translation bugs to <https://translationproject.org/team/> Full documentation at: <https://www.gnu.org/software/coreutils/df> or available locally via: info '(coreutils) df invocation'
df
หรือ df -k
หน่วยเป็น K
$ df Filesystem 1K-blocks Used Available Use% Mounted on /dev/sdc 263174212 1114200 248621856 1% / none 8119736 28 8119708 1% /mnt/wslg none 8119736 4 8119732 1% /mnt/wsl tools 981111804 490438048 490673756 50% /init none 8117652 0 8117652 0% /dev none 8119736 0 8119736 0% /run none 8119736 0 8119736 0% /run/lock none 8119736 0 8119736 0% /run/shm none 8119736 0 8119736 0% /run/user tmpfs 8119736 0 8119736 0% /sys/fs/cgroup drivers 981111804 490438048 490673756 50% /usr/lib/wsl/drivers lib 981111804 490438048 490673756 50% /usr/lib/wsl/lib none 8119736 76 8119660 1% /mnt/wslg/versions.txt none 8119736 76 8119660 1% /mnt/wslg/doc drvfs 981111804 490438048 490673756 50% /mnt/c
df -m
หน่วยเป็น M
$ df -m Filesystem 1M-blocks Used Available Use% Mounted on /dev/sdc 257007 1089 242795 1% / none 7930 1 7930 1% /mnt/wslg none 7930 1 7930 1% /mnt/wsl tools 958117 478944 479174 50% /init none 7928 0 7928 0% /dev none 7930 0 7930 0% /run none 7930 0 7930 0% /run/lock none 7930 0 7930 0% /run/shm none 7930 0 7930 0% /run/user tmpfs 7930 0 7930 0% /sys/fs/cgroup drivers 958117 478944 479174 50% /usr/lib/wsl/drivers lib 958117 478944 479174 50% /usr/lib/wsl/lib none 7930 1 7930 1% /mnt/wslg/versions.txt none 7930 1 7930 1% /mnt/wslg/doc drvfs 958117 478944 479174 50% /mnt/c
df -h
human-readable
$ df -h Filesystem Size Used Avail Use% Mounted on /dev/sdc 251G 1.1G 238G 1% / none 7.8G 28K 7.8G 1% /mnt/wslg none 7.8G 4.0K 7.8G 1% /mnt/wsl tools 936G 468G 468G 50% /init none 7.8G 0 7.8G 0% /dev none 7.8G 0 7.8G 0% /run none 7.8G 0 7.8G 0% /run/lock none 7.8G 0 7.8G 0% /run/shm none 7.8G 0 7.8G 0% /run/user tmpfs 7.8G 0 7.8G 0% /sys/fs/cgroup drivers 936G 468G 468G 50% /usr/lib/wsl/drivers lib 936G 468G 468G 50% /usr/lib/wsl/lib none 7.8G 76K 7.8G 1% /mnt/wslg/versions.txt none 7.8G 76K 7.8G 1% /mnt/wslg/doc drvfs 936G 468G 468G 50% /mnt/c
base64
transforms data read from a file, or standard input, into (or from) base64 encoded form. The base64 encoded form uses printable ASCII characters to represent binary data. Synopses:
base64 [option]… [file] base64 --decode [option]… [file]
Example#1: Encoding text data
$ echo 'linuxhint.com' | base64
Example#2: Decoding text data
$ echo 'bGludXhoaW50LmNvbQo=' | base64 --decode
Example#3: Encoding text file
$ base64 sample.txt
$ base64 sample.txt > encodedData.txt $ cat encodedData.txt
Example#4: Decoding text file
$ base64 -d encodedData.txt
$ base64 --decode encodedData.txt > originalData.txt $ cat originalData.txt
md5sum
computes a 128-bit checksum (or fingerprint or message-digest) for each specified file.
Syntax :
md5sum [OPTION]... [FILE]...
$ md5sum index.png 4191736479ed247941e1bf20830618ad index.png
Command usage examples with options :
Example 1: Store the MD5 checksum in file and then verify it.
$ md5sum /home/mandeep/test/test.cpp > checkmd5.md5
It will store the MD5 checksum for test.cpp in file checkmd5.md5
$ md5sum -c checkmd5.md5
It will verify the contents of file
Output :
/home/mandeep/test/test.cpp: OK
After changing the contents of file checkmd5.md5, the output will be :
/home/mandeep/test/test.cpp: FAILED md5sum: WARNING: 1 computed checksum did NOT match
The first five lines of Linux’s top command
top
displays uptime informationTasks
displays process status information%Cpu(s)
displays various processor valuesMiB Mem
displays physical memory utilizationMiB Swap
displays virtual memory utilization