Bash Tips
Printf
Note
Using a leading 0 is going to be octal. Using a lead 0x is going to be hexadecimal.
Width
Note
-
here in output means space.
read command
while loop
examples
For Loops
Examples
seq
Note
You can also use {A..Z}
, {a..f}
or {1..10}
in for loops.
Dealing with files
List/Array
Functions
Export functions
Case Statement
If-Then-Else Statement
Example
if
grep -q important myfile
then
echo myfile has important stuff
else
echo myfile does not have important stuff
fi
Extra
File name and path
Note
This code is inside the script file.
To get name of script file
To get full path of the file
To get full path but move one directory up
Progress bar
echo -ne '##### (33%)\r'
sleep 1
echo -ne '############# (66%)\r'
sleep 1
echo -ne '####################### (100%)\r'
echo -ne '\n'
Bash parsing and expansion
- Brace expansion
{one,two,three}
{1..10} or {a..z}
pre{d,l}ate
{{1..3},{a..c}} => 1,2,3,a,b,c
{1..3}{a..c} => 1a,1b,1c,2a,...,3c
{01..13..3} => 01,04,07,10,13
{a..h..3} => a,d,g
- Tilde expansion
- Parameter and variable expansion
var=whatever
$var or ${var} => whatever
echo $var “$var” #are having different result if there are white spaces
- Arithmetic expansion
- Command substitution
Note
If command substitution is not quoted, word splitting and pathname expansion are performed on the result.
- Word splitting
The result of parameter and arithmetic expansion, as well as command substitution, are subject to word splitting if the were NOT QUETED
Note
Word splitting is based on value of IFS (Internal Field Separator). IFS default value is space, tab, and newline. (IFS=$' \t\n'). You can change IFS value to any value.
- Pathname expansion
Char in use are *, ?, and []
list files starting with capital D.
list files which the second char is a.
list files which there is at least one number in there name.
- Process substitution
Parameter Expansion
empty or unset variable
-
Default
- echo {var:-default} => default if it is not set and empty string
- echo {var-default} => default if it is not set
-
Alternative
- echo {var:+alter} => alter if it is set and not empty string
- echo {var+alter} => alter if it is set
-
Default with assignment
- echo {var:=default} => default if it is not set and empty string, assign default to var as well
- echo {var=default} => default if it is not set, assign default to var as well.
-
Message
- echo {var:?message} => display error message if it is not set and empty string
- echo {var?message} => display error message if it is not set
** Length of var
Remove Pattern
- Short from end
- Long from end
- Short from beginning
- Long from beginning
Replace pattern
Substring var:offset:length
Negative offset