You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
name="Sovon"# No spaces around =echo"$name"# Use double quotesecho"${name}_suffix"# Braces for clarityreadonly PI=3.14 # Constantunset name # Delete variable
Special Variables
Variable
Meaning
$0
Script name
$1-$9
Arguments
$#
Number of arguments
$@
All arguments (separate)
$*
All arguments (single string)
$?
Last exit code
$$
Script PID
$!
Last background PID
Conditionals
if [[ condition ]];then
commands
elif [[ condition ]];then
commands
else
commands
fi
Test Operators
Operator
Description
-z "$s"
String is empty
-n "$s"
String is not empty
"$a" == "$b"
Strings equal
"$a" != "$b"
Strings not equal
$a -eq $b
Numbers equal
$a -ne $b
Not equal
$a -lt $b
Less than
$a -gt $b
Greater than
-f file
File exists
-d dir
Directory exists
-r file
Readable
-w file
Writable
-x file
Executable
Loops
# For loopforiin 1 2 3;doecho$i;doneforiin {1..10};doecho$i;doneforfilein*.txt;doecho"$file";donefor((i=0; i<10; i++));doecho$i;done# While loopwhile [[ condition ]];do commands;donewhileread -r line;doecho"$line";done< file.txt
# Until loopuntil [[ condition ]];do commands;done
Functions
greet() {
local name=$1# Local variableecho"Hello, $name!"return 0
}
greet "Sovon"
result=$(greet "World")# Capture output
Arrays
arr=(a b c d)
echo${arr[0]}# First elementecho${arr[@]}# All elementsecho${#arr[@]}# Length
arr+=(e) # Appendunset arr[1] # Deleteforitemin"${arr[@]}";doecho"$item";done
# Default values${var:-default}# Use default if unset${var:=default}# Set and use default# Command substitution
result=$(command)
today=$(date +%Y%m%d)# Arithmetic((count++))
result=$((a + b))# Ternary
[[ $a-gt$b ]] &&echo"yes"||echo"no"