49 Commits

Author SHA1 Message Date
671c0eb16f update comment 2023-03-11 17:16:29 +00:00
51d112b5ce Merge pull request #45 from chapmanjacobd/patch-3
Use ctrl+d instead of ctrl+c
2023-03-12 01:14:06 +08:00
40c3b7d7b8 update title for bash strict mode, add command to turn it off 2023-03-11 17:08:42 +00:00
6ecdb7b85e Merge pull request #46 from chapmanjacobd/patch-4
add more info about BASH options
2023-03-12 00:58:05 +08:00
23a1efa249 add examples for 'current time point for N days ago or after N days' 2023-03-11 16:21:26 +00:00
a606d6be45 Merge pull request #48 from PoplarYang/master
fix typo '//dev/shm/200m' and  add 'current time point for N days ago or after N days'
2023-03-12 00:07:23 +08:00
16197f576e Merge pull request #29 from siansiansu/formatExampleCode
format bash commands
2023-03-11 16:40:42 +08:00
232900349a fix typo
Co-authored-by: kang <1115610574@qq.com>
2022-05-17 18:07:22 +08:00
3cf8bdfe46 add 'current time point for N days ago or after' 2022-05-16 00:33:16 +08:00
794d4ba7b3 fix typo "//dev/shm" 2022-05-16 00:13:47 +08:00
3276c74d49 add more info about BASH options 2022-05-14 16:08:29 -05:00
f459755ade Use ctrl+d instead of ctrl+c 2022-05-14 13:10:26 -05:00
7d33353ca8 make some parts of example code more consistent
Signed-off-by: alexsu <alexsu@17.media>
2022-05-10 12:21:11 +08:00
a59c8598b0 edfixed grep command "Regex with or without a certain character" 2022-05-09 00:18:05 +08:00
c70067d38f edRemove ‘ ’ style quotes from README.ME 2022-05-09 00:15:04 +08:00
bca6221ed3 edadd comm in "data wrangling" 2022-05-09 00:01:41 +08:00
0103101550 edit "Run last command" 2022-05-08 23:35:19 +08:00
bab726081b fixed example for Variable command 2022-05-08 23:33:28 +08:00
7d40456576 fixed content order 2022-05-08 23:07:47 +08:00
ab2ecc058d fixing example output for look command 2022-05-08 01:38:02 +08:00
9dbc77ba6e Merge pull request #28 from NateEag/patch-1
Fix typo in README.md (singer -> single)
2022-05-08 01:32:45 +08:00
8b2e16f0c1 Merge pull request #33 from JacksonBailey/patch-1
Variable substitution changes
2022-05-08 01:30:26 +08:00
18134f72c9 Merge pull request #30 from ember91/master
Fix spelling errors
2022-05-08 01:20:06 +08:00
b1137da792 Merge pull request #24 from linus/patch-2
Use correct quoting
2022-05-08 01:04:52 +08:00
b912cc99bf Merge pull request #23 from linus/patch-1
Use equivalent regex with PCRE
2022-05-08 01:02:27 +08:00
b07665cb43 Merge pull request #22 from herrcykel/patch-1
Simplify glob expression
2022-05-08 00:58:25 +08:00
7010074d16 Merge pull request #35 from chapeupreto/fixes
fix typo and markdown formatting issues
2022-05-08 00:54:56 +08:00
12023778bd fix typo and markdown formatting
Signed-off-by: Rod Elias <rodiney@gmail.com>
2022-05-06 10:50:27 -03:00
dc268515b7 Variable substitution changes
Clarify documentation and give a few more examples
2022-05-04 15:58:25 -04:00
d2549128c7 Fix spelling errors
Signed-off-by: Emil Berg <emil.berg@ericsson.com>
2022-05-04 07:50:27 +02:00
bd9a732dba Correct the description of Esc + c (Alt+c)
Signed-off-by: Страхиња Радић <contact@strahinja.org>
2022-05-04 07:47:31 +02:00
c136e0f36f Fix typo in README.md (singer -> single) 2022-05-03 21:45:55 -04:00
O
8ab7cf7a6d Simplify glob expression
Signed-off-by: O <herrcykel@users.noreply.github.com>
2022-05-03 22:15:57 +02:00
a97dcf2a3b Use equivalent regex with PCRE
Use the equivalent regex with PCRE.

`[0-9]*` (and `\d*`) will output each integer, e.g.:

```bash
echo 17 | grep -o '[0-9]*'
```

Whereas `\d` will split it into digits, e.g.:

```bash
echo 17 | grep -oP '\d'
```

Signed-off-by: Linus G Thiel <linus@yesbabyyes.se>
2022-05-03 22:02:09 +02:00
0f5fa26f06 Use correct quoting
Unquote the sed expression.

Signed-off-by: Linus G Thiel <linus@yesbabyyes.se>
2022-05-03 22:01:42 +02:00
c2b96736bd Merge pull request #21 from Strahinja/master
Correct the description of Esc + c (Alt+c, M-c)
2022-05-03 12:21:52 +08:00
8dcfa4904b Correct the description of Esc + c (Alt+c)
Signed-off-by: Страхиња Радић <contact@strahinja.org>
2022-01-26 18:17:03 +01:00
ce13d4af19 Merge pull request #20 from valerionew/patch-1
Swap * and ? in bash globbing sections to match with correct comments
2021-08-13 19:03:16 +08:00
81ec32bfb9 Swap * and ? in bash globbing sections to match with correct comments
Signed-off-by: valerionew <valerionappi995@gmail.com>
2021-07-01 15:05:55 +02:00
954f42c06a fixed typo in file name
xargs using With sed
2021-05-16 16:17:31 +08:00
c1c3f8bcb5 Merge pull request #19 from WardMaes/master
Add instructions to exit virtual environment
2021-05-06 17:30:17 +08:00
26db64f1b2 Add deactivate command
Signed-off-by: Ward <WardMaes@users.noreply.github.com>
2021-04-11 11:40:52 +02:00
5e32496e5d Merge branch 'master' of https://github.com/onceupon/Bash-Oneliner 2021-03-16 22:10:53 +08:00
f1e9f30e78 + find 1. Recursively count all the files in a directory
+ Condition and loop
1.  Using test command, to test if the length of variable is nonzero

+ Others
1. Create a screen and name it 'test'

+ Time
1. Get the seconds since epoch (Jan 1 1970) for a given date (e.g Mar 16 
2021)
2. Convert the number of seconds since epoch back to date

+ fix some markdown syntax issue
2021-03-16 22:10:49 +08:00
248ae4c50e Merge branch 'master' of https://github.com/onceupon/Bash-Oneliner 2021-03-16 22:08:23 +08:00
5740e44d62 + find 1. Recursively count all the files in a directory
+ Condition and loop
1.  Using test command, to test if the length of variable is nonzero

+ Others
1. Create a screen and name it 'test'

+ Time
1. Get the seconds since epoch (Jan 1 1970) for a given date (e.g Mar 16 
2021)
2. Convert the number of seconds since epoch back to date

+ fix some markdown syntax issue
2021-03-16 22:08:02 +08:00
19d402cc84 + find
1. Recursively count all the files in a directory

+ Condition and loop
1.  Using test command, to test if the length of variable is nonzero

+ Others
1. Create a screen and name it 'test'

+ Time
1. Get the seconds since epoch (Jan 1 1970) for a given date (e.g Mar 16 
2021)
2. Convert the number of seconds since epoch back to date

+ fix some markdown syntax issue
2021-03-16 22:03:57 +08:00
244a568bd7 fix typo mentioned in issue https://github.com/onceupon/Bash-Oneliner/issues/18 2021-03-16 20:13:56 +08:00
093edef55a + time
returns the current time with nanoseconds.
2021-03-16 19:43:41 +08:00

265
README.md
View File

@ -1,7 +1,7 @@
# Bash-Oneliner # Bash-Oneliner
I am glad that you are here! I was working on bioinformatics a few years ago and was amazed by those single-word bash commands which are much faster than my dull scripts, time saved through learning command-line shortcuts and scripting. Recent years I am working on cloud computing and I keep recording those useful commands here. Not all of them is oneliner, but i put effort on making them brief and swift. I am mainly using Ubuntu, Amazon Linux, RedHat, Linux Mint, Mac and CentOS, sorry if the commands don't work on your system. I am glad that you are here! I was working on bioinformatics a few years ago and was amazed by those single-word bash commands which are much faster than my dull scripts, time saved through learning command-line shortcuts and scripting. Recent years I am working on cloud computing and I keep recording those useful commands here. Not all of them is oneliner, but i put effort on making them brief and swift. I am mainly using Ubuntu, Amazon Linux, RedHat, Linux Mint, Mac and CentOS, sorry if the commands don't work on your system.
This blog will focus on simple bash commands for parsing data and Linux system maintenance that i acquired from work and LPIC exam. I apologize that there are no detailed citation for all the commands, but they are probably from dear Google and Stackoverflow. This blog will focus on simple bash commands for parsing data and Linux system maintenance that i acquired from work and LPIC exam. I apologize that there are no detailed citation for all the commands, but they are probably from dear Google and Stack Overflow.
English and bash are not my first language, please correct me anytime, thank you. English and bash are not my first language, please correct me anytime, thank you.
If you know other cool commands, please teach me! If you know other cool commands, please teach me!
@ -12,13 +12,13 @@ Here's a more stylish version of [Bash-Oneliner](https://onceupon.github.io/Bash
- [Terminal Tricks](#terminal-tricks) - [Terminal Tricks](#terminal-tricks)
- [Variable](#variable) - [Variable](#variable)
- [Math](#math)
- [Grep](#grep) - [Grep](#grep)
- [Sed](#sed) - [Sed](#sed)
- [Awk](#awk) - [Awk](#awk)
- [Xargs](#xargs) - [Xargs](#xargs)
- [Find](#find) - [Find](#find)
- [Condition and Loop](#condition-and-loop) - [Condition and Loop](#condition-and-loop)
- [Math](#math)
- [Time](#time) - [Time](#time)
- [Download](#download) - [Download](#download)
- [Random](#random) - [Random](#random)
@ -57,7 +57,7 @@ Esc + u
Esc + l Esc + l
# converts text from cursor to the end of the word to lowercase. # converts text from cursor to the end of the word to lowercase.
Esc + c Esc + c
# converts letter under the cursor to uppercase. # converts letter under the cursor to uppercase, rest of the word to lowercase.
``` ```
##### Run history number (e.g. 53) ##### Run history number (e.g. 53)
```bash ```bash
@ -69,7 +69,6 @@ Esc + c
!! !!
# run the previous command using sudo # run the previous command using sudo
sudo !! sudo !!
# of course you need to enter your password
``` ```
##### Run last command and change some parameter using caret substitution (e.g. last command: echo 'aaa' -> rerun as: echo 'bbb') ##### Run last command and change some parameter using caret substitution (e.g. last command: echo 'aaa' -> rerun as: echo 'bbb')
@ -98,16 +97,16 @@ sudo !!
##### Bash globbing ##### Bash globbing
```bash ```bash
# '*' serves as a "wild card" for filename expansion. # '*' serves as a "wild card" for filename expansion.
/b?n/?at #/bin/cat
# '?' serves as a single-character "wild card" for filename expansion.
/etc/pa*wd #/etc/passwd /etc/pa*wd #/etc/passwd
# [] serves to match the character from a range. # '?' serves as a single-character "wild card" for filename expansion.
/b?n/?at #/bin/cat
# '[]' serves to match the character from a range.
ls -l [a-z]* #list all files with alphabet in its filename. ls -l [a-z]* #list all files with alphabet in its filename.
# {} can be used to match filenames with more than one patterns # '{}' can be used to match filenames with more than one patterns
ls {*.sh,*.py} #list all .sh and .py files ls *.{sh,py} #list all .sh and .py files
``` ```
##### Some handy environment variables ##### Some handy environment variables
@ -135,9 +134,19 @@ $HOSTNAME current hostname
##### Variable substitution within quotes ##### Variable substitution within quotes
```bash ```bash
# foo=bar # foo=bar
echo $foo
# bar
echo "$foo"
# bar
# single quotes cause variables to not be expanded
echo '$foo'
# $foo
# single quotes within double quotes will not cancel expansion and will be part of the output
echo "'$foo'" echo "'$foo'"
# 'bar' # 'bar'
# double/single quotes around single quotes make the inner single quotes expand variables # doubled single quotes act as double quotes making variables expand
echo ''$foo''
# bar
``` ```
##### Get the length of variable ##### Get the length of variable
```bash ```bash
@ -178,9 +187,11 @@ echo ${var[@]#0}
```bash ```bash
{var//a/,} {var//a/,}
``` ```
##### Grep lines with strings from a file (e.g. lines with 'stringA or 'stringB' or 'stringC')
```bash ```bash
#with grep #with grep
test="god the father" test="stringA stringB stringC"
grep ${test// /\\\|} file.txt grep ${test// /\\\|} file.txt
# turning the space into 'or' (\|) in grep # turning the space into 'or' (\|) in grep
``` ```
@ -205,9 +216,9 @@ echo "$bar" # foo
```bash ```bash
echo $(( 10 + 5 )) #15 echo $(( 10 + 5 )) #15
x=1 x=1
echo $(( x++ )) #1 , notice that it is still 1, since it's post-incremen echo $(( x++ )) #1 , notice that it is still 1, since it's post-increment
echo $(( x++ )) #2 echo $(( x++ )) #2
echo $(( ++x )) #4 , notice that it is not 3 since it's pre-incremen echo $(( ++x )) #4 , notice that it is not 3 since it's pre-increment
echo $(( x-- )) #4 echo $(( x-- )) #4
echo $(( x-- )) #3 echo $(( x-- )) #3
echo $(( --x )) #1 echo $(( --x )) #1
@ -265,7 +276,7 @@ echo "var=5;--var"| bc
##### Type of grep ##### Type of grep
```bash ```bash
grep = grep -G # Basic Regular Expression (BRE) grep = grep -G # Basic Regular Expression (BRE)
fgrep = grep -F # fixed text, ignoring meta-charachetrs fgrep = grep -F # fixed text, ignoring meta-characters
egrep = grep -E # Extended Regular Expression (ERE) egrep = grep -E # Extended Regular Expression (ERE)
pgrep = grep -P # Perl Compatible Regular Expressions (PCRE) pgrep = grep -P # Perl Compatible Regular Expressions (PCRE)
rgrep = grep -r # recursive rgrep = grep -r # recursive
@ -280,15 +291,15 @@ grep -c "^$"
```bash ```bash
grep -o '[0-9]*' grep -o '[0-9]*'
#or #or
grep -oP '\d' grep -oP '\d*'
``` ```
##### Grep integer with certain number of digits (e.g. 3) ##### Grep integer with certain number of digits (e.g. 3)
```bash ```bash
grep [0-9]\{3\} grep '[0-9]\{3\}'
# or # or
grep -E [0-9]{3} grep -E '[0-9]{3}'
# or # or
grep -P \d{3} grep -P '\d{3}'
``` ```
##### Grep only IP address ##### Grep only IP address
@ -395,14 +406,14 @@ grep 'A\|B\|C\|D'
grep 'A.*B' grep 'A.*B'
``` ```
##### Regex any singer character (e.g. ACB or AEB) ##### Regex any single character (e.g. ACB or AEB)
```bash ```bash
grep 'A.B' grep 'A.B'
``` ```
##### Regex with or without a certain character (e.g. color or colour) ##### Regex with or without a certain character (e.g. color or colour)
```bash ```bash
grep colou?r grep 'colou\?r'
``` ```
##### Grep all content of a fileA from fileB ##### Grep all content of a fileA from fileB
@ -456,9 +467,10 @@ sed 1,100d filename
##### Remove lines with string (e.g. 'bbo') ##### Remove lines with string (e.g. 'bbo')
```bash ```bash
sed "/bbo/d" filename sed "/bbo/d" filename
- case insensitive: # case insensitive:
sed "/bbo/Id" filename sed "/bbo/Id" filename
``` ```
##### Remove lines whose nth character not equal to a value (e.g. 5th character not equal to 2) ##### Remove lines whose nth character not equal to a value (e.g. 5th character not equal to 2)
```bash ```bash
sed -E '/^.{5}[^2]/d' sed -E '/^.{5}[^2]/d'
@ -510,7 +522,7 @@ sed -i '1s/^/[/' file
##### Add string at certain line number (e.g. add 'something' to line 1 and line 3) ##### Add string at certain line number (e.g. add 'something' to line 1 and line 3)
```bash ```bash
sed -e '1isomething -e '3isomething' sed -e '1isomething' -e '3isomething'
``` ```
##### Add string to end of file (e.g. "]") ##### Add string to end of file (e.g. "]")
@ -537,7 +549,7 @@ sed -e 's/$/\}\]/' filename
sed 's/.\{4\}/&\n/g' sed 's/.\{4\}/&\n/g'
``` ```
##### Concatenate/combine/join files with a seperator and next line (e.g separate by ",") ##### Concatenate/combine/join files with a separator and next line (e.g separate by ",")
```bash ```bash
sed -s '$a,' *.json > all.json sed -s '$a,' *.json > all.json
``` ```
@ -774,7 +786,7 @@ awk '{printf("%s\t%s\n",NR,$0)}'
##### Break combine column data into rows ##### Break combine column data into rows
```bash ```bash
# For example, seperate the following content: # For example, separate the following content:
# David cat,dog # David cat,dog
# into # into
# David cat # David cat
@ -894,7 +906,7 @@ find /dir/to/A -type f -name "*.py" -print 0| xargs -0 -r -I file cp -v -p file
##### With sed ##### With sed
```bash ```bash
ls |xargs -n1 -I file sed -i '/^Pos/d' filename ls |xargs -n1 -I file sed -i '/^Pos/d' file
``` ```
##### Add the file name to the first line of file ##### Add the file name to the first line of file
@ -982,6 +994,11 @@ find . -type f -empty
find . -type f -empty -delete find . -type f -empty -delete
``` ```
##### Recursively count all the files in a directory
```bash
find . -type f | wc -l
```
## Condition and loop ## Condition and loop
[[back to top](#handy-bash-one-liners)] [[back to top](#handy-bash-one-liners)]
@ -991,7 +1008,7 @@ find . -type f -empty -delete
if [[ "$c" == "read" ]]; then outputdir="seq"; else outputdir="write" ; fi if [[ "$c" == "read" ]]; then outputdir="seq"; else outputdir="write" ; fi
# Test if myfile contains the string 'test': # Test if myfile contains the string 'test':
if grep -q hello myfile; then if grep -q hello myfile; then echo -e "file contains the string!" ; fi
# Test if mydir is a directory, change to it and do other stuff: # Test if mydir is a directory, change to it and do other stuff:
if cd mydir; then if cd mydir; then
@ -1001,9 +1018,12 @@ else
fi fi
# if variable is null # if variable is null
if [ ! -s "myvariable" ] if [ ! -s "myvariable" ]; then echo -e "variable is null!" ; fi
#True of the length if "STRING" is zero. #True of the length if "STRING" is zero.
# Using test command (same as []), to test if the length of variable is nonzero
test -n "$myvariable" && echo myvariable is "$myvariable" || echo myvariable is not set
# Test if file exist # Test if file exist
if [ -e 'filename' ] if [ -e 'filename' ]
then then
@ -1017,16 +1037,17 @@ then
fi fi
# Test if the value of x is greater or equal than 5 # Test if the value of x is greater or equal than 5
if [ "$x" -ge 5 ]; then if [ "$x" -ge 5 ]; then echo -e "greater or equal than 5!" ; fi
# Test if the value of x is greater or equal than 5, in bash/ksh/zsh: # Test if the value of x is greater or equal than 5, in bash/ksh/zsh:
if ((x >= 5)); then if ((x >= 5)); then echo -e "greater or equal than 5!" ; fi
# Use (( )) for arithmetic operation # Use (( )) for arithmetic operation
if ((j==u+2)) if ((j==u+2)); then echo -e "j==u+2!!" ; fi
# Use [[ ]] for comparison # Use [[ ]] for comparison
if [[ $age -gt 21 ]] if [[ $age -gt 21 ]]; then echo -e "forever 21!!" ; fi
``` ```
[More if commands](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html) [More if commands](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html)
@ -1106,6 +1127,45 @@ date +%F
# or # or
date +'%d-%b-%Y-%H:%M:%S' date +'%d-%b-%Y-%H:%M:%S'
# 10-Apr-2020-21:54:40 # 10-Apr-2020-21:54:40
# Returns the current time with nanoseconds.
date +"%T.%N"
# 11:42:18.664217000
# Get the seconds since epoch (Jan 1 1970) for a given date (e.g Mar 16 2021)
date -d "Mar 16 2021" +%s
# 1615852800
# or
date -d "Tue Mar 16 00:00:00 UTC 2021" +%s
# 1615852800
# Convert the number of seconds since epoch back to date
date --date @1615852800
# Tue Mar 16 00:00:00 UTC 2021
```
##### Print current time point for N days ago or N days after
```bash
# print current date first (for the following example)
date +"%F %H:%M:%S"
# 2023-03-11 16:17:09
# print the time that is 1 day ago
date -d"1 day ago" +"%F %H:%M:%S"
# 2023-03-10 16:17:09
# print the time that is 7 days ago
date -d"7 days ago" +"%F %H:%M:%S"
# 2023-03-04 16:17:09
# print the time that is a week ago
date -d"1 week ago" +"%F %H:%M:%S"
# 2023-03-04 16:17:09
# add 1 day to date
date -d"-1 day ago" +"%F %H:%M:%S"
# 2023-03-12 16:17:09
``` ```
##### wait for random duration (e.g. sleep 1-5 second, like adding a jitter) ##### wait for random duration (e.g. sleep 1-5 second, like adding a jitter)
@ -1707,6 +1767,18 @@ du -h
du -sk /var/log/* |sort -rn |head -10 du -sk /var/log/* |sort -rn |head -10
``` ```
##### check the Inode utilization
```
df -i
# Filesystem Inodes IUsed IFree IUse% Mounted on
# devtmpfs 492652 304 492348 1% /dev
# tmpfs 497233 2 497231 1% /dev/shm
# tmpfs 497233 439 496794 1% /run
# tmpfs 497233 16 497217 1% /sys/fs/cgroup
# /dev/nvme0n1p1 5037976 370882 4667094 8% /
# tmpfs 497233 1 497232 1% /run/user/1000
```
##### Show all file system type ##### Show all file system type
```bash ```bash
df -TH df -TH
@ -2163,6 +2235,7 @@ sar -n ALL
# reading SAR log file using -f # reading SAR log file using -f
sar -f /var/log/sa/sa31|tail sar -f /var/log/sa/sa31|tail
```
##### Reading from journal file ##### Reading from journal file
```bash ```bash
@ -2380,7 +2453,7 @@ nc -vw5 google.com 22
# From server A: # From server A:
$ sudo nc -l 80 $ sudo nc -l 80
# then you can connect to the 80 port from another server (e.g. server B): # then you can connect to the 80 port from another server (e.g. server B):
# e.g. telent <server A IP address> 80 # e.g. telnet <server A IP address> 80
# then type something in server B # then type something in server B
# and you will see the result in server A! # and you will see the result in server A!
``` ```
@ -2522,16 +2595,16 @@ sudo iptables A INPUT s <IP> -p tcp dport 80 j DROP
```bash ```bash
# If file is not specified, the file /usr/share/dict/words is used. # If file is not specified, the file /usr/share/dict/words is used.
look phy|head -n 10 look phy|head -n 10
# Phil # phycic
# Philadelphia # Phyciodes
# Philadelphia's # phycite
# Philby # Phycitidae
# Philby's # phycitol
# Philip # phyco-
# Philippe # phycochrom
# Philippe's # phycochromaceae
# Philippians # phycochromaceous
# Philippine # phycochrome
``` ```
##### Repeat printing string n times (e.g. print 'hello world' five times) ##### Repeat printing string n times (e.g. print 'hello world' five times)
@ -2589,6 +2662,40 @@ sdiff fileA fileB
diff fileA fileB --strip-trailing-cr diff fileA fileB --strip-trailing-cr
``` ```
##### Find common/differing lines
```bash
# having two sorted and uniqed files (for example after running `$ sort -uo fileA fileA` and same for fileB):
# ------
# fileA:
# ------
# joey
# kitten
# piglet
# puppy
# ------
# fileB:
# ------
# calf
# chick
# joey
# puppy
#
# Find lines in both files
comm -12 fileA fileB
# joey
# puppy
#
# Find lines in fileB that are NOT in fileA
comm -13 fileA fileB
# calf
# chick
#
# Find lines in fileA that are NOT in fileB
comm -23 fileA fileB
# kitten
# piglet
```
##### Number a file (e.g. fileA) ##### Number a file (e.g. fileA)
```bash ```bash
@ -2753,12 +2860,28 @@ var=$((var+1))
cat filename|rev|cut -f1|rev cat filename|rev|cut -f1|rev
``` ```
##### Cat to a file ##### Create or replace a file with contents
```bash ```bash
cat >myfile cat >myfile
let me add sth here let me add sth here
exit by control + c # exit with ctrl+d
^C
# or using tee
tee myfile
let me add sth else here
# exit with ctrl+d
```
##### Append to a file with contents
```bash
cat >>myfile
let me add sth here
# exit with ctrl+d
# or using tee
tee -a myfile
let me add sth else here
# exit with ctrl+d
``` ```
##### Clear the contents of a file (e.g. filename) ##### Clear the contents of a file (e.g. filename)
@ -2877,6 +3000,13 @@ cal
# only display November # only display November
cal -m 11 cal -m 11
``` ```
##### Convert the hexadecimal MD5 checksum value into its base64-encoded format.
```bash
openssl md5 -binary /path/to/file| base64
# NWbeOpeQbtuY0ATWuUeumw==
```
##### Forces applications to use the default language for output ##### Forces applications to use the default language for output
```bash ```bash
export LC_ALL=C export LC_ALL=C
@ -3098,7 +3228,7 @@ scp -r directoryname user@ip:/path/to/send
echo $? echo $?
``` ```
##### Extract .xf ##### Extract .xz
``` ```
unxz filename.tar.xz unxz filename.tar.xz
# then # then
@ -3138,8 +3268,7 @@ yes n
# or 'anything': # or 'anything':
yes anything yes anything
# For example: # pipe yes to other command
```bash
yes | rm -r large_directory yes | rm -r large_directory
``` ```
@ -3150,9 +3279,9 @@ fallocate -l 10G 10Gigfile
##### Create dummy file of certain size (e.g. 200mb) ##### Create dummy file of certain size (e.g. 200mb)
```bash ```bash
dd if=/dev/zero of=//dev/shm/200m bs=1024k count=200 dd if=/dev/zero of=/dev/shm/200m bs=1024k count=200
# or # or
dd if=/dev/zero of=//dev/shm/200m bs=1M count=200 dd if=/dev/zero of=/dev/shm/200m bs=1M count=200
# Standard output: # Standard output:
# 200+0 records in # 200+0 records in
@ -3165,9 +3294,29 @@ dd if=/dev/zero of=//dev/shm/200m bs=1M count=200
watch -n 1 wc -l filename watch -n 1 wc -l filename
``` ```
##### Use Bash Strict Mode
```bash
# These options can make your code safer but, depending on how your pipeline is written, it might be too aggressive
# or it might not catch the errors that you are interested in
# for reference see https://gist.github.com/mohanpedala/1e2ff5661761d3abd0385e8223e16425
# and https://mywiki.wooledge.org/BashPitfalls#set_-euo_pipefail
set -o errexit # exit immediately if a pipeline returns a non-zero status
set -o errtrace # trap ERR from shell functions, command substitutions, and commands from subshell
set -o nounset # treat unset variables as an error
set -o pipefail # pipe will exit with last non-zero status, if applicable
set -Eue -o pipefail # shorthand for above (pipefail has no short option)
```
##### Print commands and their arguments when execute (e.g. echo `expr 10 + 20 `) ##### Print commands and their arguments when execute (e.g. echo `expr 10 + 20 `)
```bash ```bash
set -x; echo `expr 10 + 20 ` set -x; echo `expr 10 + 20 `
# or
set -o xtrace; echo `expr 10 + 20 `
# to turn it off..
set +x
``` ```
##### Print some meaningful sentences to you (install fortune first) ##### Print some meaningful sentences to you (install fortune first)
@ -3198,6 +3347,9 @@ q -d "," "select c3,c4,c5 from /path/to/file.txt where c3='foo' and c5='boo'"
# Create session and attach: # Create session and attach:
screen screen
# Create a screen and name it 'test'
screen -S test
# Create detached session foo: # Create detached session foo:
screen -S foo -d -m screen -S foo -d -m
@ -3216,15 +3368,16 @@ screen -r foo
# Kill session foo: # Kill session foo:
screen -r foo -X quit screen -r foo -X quit
# Scroll: # Scroll:
Hit your screen prefix combination (C-a / control+A), then hit Escape. # Hit your screen prefix combination (C-a / control+A), then hit Escape.
Move up/down with the arrow keys (↑ and ↓). # Move up/down with the arrow keys (↑ and ↓).
# Redirect output of an already running process in Screen: # Redirect output of an already running process in Screen:
(C-a / control+A), then hit 'H' # (C-a / control+A), then hit 'H'
# Store screen output for Screen: # Store screen output for Screen:
Ctrl+A, Shift+H # Ctrl+A, Shift+H
# You will then find a screen.log file under current directory. # You will then find a screen.log file under current directory.
``` ```
@ -3351,6 +3504,8 @@ source .venv/bin/activate
type pip type pip
# 5. Now you can install your pip package, here requirements.txt is simply a txt file containing all the packages you want. (e.g tornado==4.5.3). # 5. Now you can install your pip package, here requirements.txt is simply a txt file containing all the packages you want. (e.g tornado==4.5.3).
pip install -r requirements.txt pip install -r requirements.txt
# 6. Exit virtual environment
deactivate
``` ```