#!/bin/bashNAME="Payam"echo "Hello $NAME!"exit 0
varname=value # defines a variablevarname=value command # defines a variable to be in the environment of a particular subprocessecho $varname # checks a variable's valueread <varname> # reads a string from the input and assigns it to a variablelet <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, %export VARNAME=value # defines an environment variable (will be available in subprocesses)
#Special shell variablesecho $$ # prints process ID of the current shellecho $! # prints process ID of the most recently invoked background jobecho $? # displays the exit status of the last commandecho $0 # display Filename of the shell script
\c #Take character c literally.`cmd` #Run cmd and replace it in the line of code with its output."whatever" #Take whatever literally, after first interpreting $, `...`, \'whatever' #Take whatever absolutely literally.#Example:match=`ls *.bak` #Puts names of .bak files into shell variable match.echo \* #Echos * to screen, not all filename as in: echo *echo '$1$2hello' #Writes literally $1$2hello on screen.echo "$1$2hello" #Writes value of parameters 1 and 2 and string hello.
python hello.py > output.txt # stdout to (file)python hello.py >> output.txt # stdout to (file), appendpython hello.py 2> error.log # stderr to (file)python hello.py 2>&1 # stderr to stdoutpython hello.py 2>/dev/null # stderr to (null)python hello.py &>/dev/null # stdout and stderr to (null)python hello.py < foo.txt # feed foo.txt to stdin for python
{A,B} Same as A B{A,B}.js Same as A.js B.js{1..5} Same as 1 2 3 4 5
name="John"echo ${name}echo ${name/J/j} #=> "john" (substitution)echo ${name:0:2} #=> "Jo" (slicing)echo ${name::2} #=> "Jo" (slicing)echo ${name::-1} #=> "Joh" (slicing)echo ${name:(-1)} #=> "n" (slicing from right)echo ${name:(-2):1} #=> "h" (slicing from right)echo ${food:-Cake} #=> $food or "Cake"length=2echo ${name:0:length} #=> "Jo"
STR="/path/to/foo.cpp"echo ${STR%.cpp} # /path/to/fooecho ${STR%.cpp}.o # /path/to/foo.oecho ${STR%/*} # /path/toecho ${STR##*.} # cpp (extension)echo ${STR##*/} # foo.cpp (basepath)echo ${STR#*/} # path/to/foo.cppecho ${STR##*/} # foo.cppecho ${STR/foo/bar} # /path/to/bar.cppSTR="Hello world"echo ${STR:6:5} # "world"echo ${STR: -5:5} # "world"SRC="/path/to/foo.cpp"BASE=${SRC##*/} #=> "foo.cpp" (basepath)DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
${FOO%suffix} Remove suffix${FOO#prefix} Remove prefix${FOO%%suffix} Remove long suffix${FOO##prefix} Remove long prefix${FOO/from/to} Replace first match${FOO//from/to} Replace all${FOO/%from/to} Replace suffix${FOO/#from/to} Replace prefix
${#FOO} Length of $FOO
${FOO:-val} $FOO, or val if unset (or null)${FOO:=val} Set $FOO to val if unset (or null)${FOO:+val} val if $FOO is set (and not null)${FOO:?message} Show error message and exit if $FOO is unset (or null)#Omitting the : removes the (non)nullity checks,#e.g. ${FOO-val} expands to val if unset otherwise $FOO.
# Single line comment: 'This is amulti linecomment'
${FOO:0:3} Substring (position, length)${FOO:(-3):3} Substring from the right
STR="HELLO WORLD!"echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)echo ${STR,,} #=> "hello world!" (all lowercase)STR="hello world!"echo ${STR^} #=> "Hello world!" (uppercase 1st letter)echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
In Bash, the test
command takes one of the following syntax forms:
test EXPRESSION
[ EXPRESSION ]
[[ EXPRESSION ]]
To make the script portable, prefer using the old test [
command which is available on all POSIX shells. The new upgraded version of the test
command [[
(double brackets) is supported on most modern systems using Bash, Zsh, and Ksh as a default shell. To negate the test expression, use the logical NOT
(!
) operator.
Note that a shell variable could contain a string that represents a number. If you want to check the numerical value use one of the following:
[[ NUM -eq NUM ]] Equal[[ NUM -ne NUM ]] Not equal[[ NUM -lt NUM ]] Less than[[ NUM -le NUM ]] Less than or equal[[ NUM -gt NUM ]] Greater than[[ NUM -ge NUM ]] Greater than or equal
[[ -z STRING ]] Empty string[[ -n STRING ]] Not empty string[[ STRING == STRING ]] Equal[[ STRING != STRING ]] Not Equal
[[ -e FILE ]] Exists[[ -r FILE ]] Readable[[ -h FILE ]] Symlink[[ -d FILE ]] Directory[[ -w FILE ]] Writable[[ -s FILE ]] Size is > 0 bytes[[ -f FILE ]] File[[ -x FILE ]] Executable[[ FILE1 -nt FILE2 ]] 1 is more recent than 2[[ FILE1 -ot FILE2 ]] 2 is more recent than 1[[ FILE1 -ef FILE2 ]] Same files
[[ -o noclobber ]] If OPTIONNAME is enabled[[ ! EXPR ]] Not[[ X && Y ]] And[[ X || Y ]] Or
#if Statementecho -n "Enter a number: "read VARif [[ $VAR -gt 10 ]]thenecho "The variable is greater than 10."fi
#if..else Statementecho -n "Enter a number: "read VARif [[ $VAR -gt 10 ]]thenecho "The variable is greater than 10."elseecho "The variable is equal or less than 10."fi
#if..elif..else Statementecho -n "Enter a number: "read VARif [[ $VAR -gt 10 ]]thenecho "The variable is greater than 10."elif [[ $VAR -eq 10 ]]thenecho "The variable is equal to 10."elseecho "The variable is less than 10."fi
# Nested if Statementsecho -n "Enter the first number: "read VAR1echo -n "Enter the second number: "read VAR2echo -n "Enter the third number: "read VAR3if [[ $VAR1 -ge $VAR2 ]]thenif [[ $VAR1 -ge $VAR3 ]]thenecho "$VAR1 is the largest number."elseecho "$VAR3 is the largest number."fielseif [[ $VAR2 -ge $VAR3 ]]thenecho "$VAR2 is the largest number."elseecho "$VAR3 is the largest number."fifi
#basic for loopfor i in 1 2 3 4 5doecho "Welcome $i times"done
#Basic for loopfor i in /etc/rc.*; doecho $idone
#Rangesfor i in {1..5}; doecho "Welcome $i"done
#C-Like for loopfor ((i = 0 ; i < 100 ; i++)); doecho $idone
#with step sizefor i in {5..50..5}; doecho "Welcome $i"done
n=1while [ $n -le 5 ]doecho "Welcome $n times."n=$(( n+1 ))done
#Using ((expression)) Format With The While Loopn=1while (( $n <= 5 ))doecho "Welcome $n times."n=$(( n+1 ))done
#for everwhile true; do···done
# Reading a test file:###example1/2:cat /etc/resolv.conf | while read line; doecho $linedone###example2/2:file=/etc/resolv.confwhile IFS= read -r linedoecho $linedone < "$file"### Reading A Text File With Separate Fields:file=/etc/resolv.conf# set field separator to a single white spacewhile IFS=' ' read -r f1 f2doecho "field # 1 : $f1 ==> field #2 : $f2"done < "$file"
#!/bin/bashcounter=0until [ $counter -gt 5 ]doecho Counter: $counter((counter++))done
Case/switchcase "$1" instart | up)vagrant up;;*)echo "Usage: $0 {start|stop|ssh}";;esac
# Defining functions:myfunc() {echo "hello $1"}# Same as above (alternate syntax)function myfunc() {echo "hello $1"}myfunc "John"
#Returning values:myfunc() {local myresult='some value'echo $myresult}result="$(myfunc)"
#Raising errors:myfunc() {return 1}if myfunc; thenecho "success"elseecho "failure"fi
#Arguments:$# Number of arguments$* All arguments[email protected] All arguments, starting from first$1 First argument$_ Last argument of the previous command
Defining arraysFruits=('Apple' 'Banana' 'Orange')Fruits[0]="Apple"Fruits[1]="Banana"Fruits[2]="Orange"
OperationsFruits=("${Fruits[@]}" "Watermelon") # PushFruits+=('Watermelon') # Also PushFruits=( ${Fruits[@]/Ap*/} ) # Remove by regex matchunset Fruits[2] # Remove one itemFruits=("${Fruits[@]}") # DuplicateFruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenatelines=(`cat "logfile"`) # Read from file
Working with arraysecho ${Fruits[0]} # Element #0echo ${Fruits[-1]} # Last elementecho ${Fruits[@]} # All elements, space-separatedecho ${#Fruits[@]} # Number of elementsecho ${#Fruits} # String length of the 1st elementecho ${#Fruits[3]} # String length of the Nth elementecho ${Fruits[@]:3:2} # Range (from position 3, length 2)echo ${!Fruits[@]} # Keys of all elements, space-separated
Iterationfor i in "${arrayName[@]}"; doecho $idone
Definingdeclare -A soundssounds[dog]="bark"sounds[cow]="moo"sounds[bird]="tweet"sounds[wolf]="howl"
Working with dictionariesecho ${sounds[dog]} # Dog's soundecho ${sounds[@]} # All valuesecho ${!sounds[@]} # All keysecho ${#sounds[@]} # Number of elementsunset sounds[dog] # Delete dog
IterationIterate over valuesfor val in "${sounds[@]}"; doecho $valdoneIterate over keysfor key in "${!sounds[@]}"; doecho $keydone
bash -n scriptname # don't run commands; check for syntax errors onlyset -o noexec # alternative (set option in script)bash -v scriptname # echo commands before running themset -o verbose # alternative (set option in script)bash -x scriptname # echo commands after command-line processingset -o xtrace # alternative (set option in script)
#Numeric calculations$((a + 200)) # Add 200 to $a$(($RANDOM%200)) # Random number 0..199
#Inspecting commandscommand -V cd#=> "cd is a function/alias/whatever"
#Heredoc:cat <<ENDhello worldEND
#printf:printf "Hello %s, I'm %s" Sven Olga#=> "Hello Sven, I'm Olgaprintf "1 + 1 = %d" 2#=> "1 + 1 = 2"printf "This is how you print a float: %f" 2#=> "This is how you print a float: 2.000000"
#Reading inputecho -n "Proceed? [y/n]: "read ansecho $ans#Reading Just one character:read -n 1 ans
#Getting optionswhile [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in-V | --version )echo $versionexit;;-s | --string )shift; string=$1;;-f | --flag )flag=1;;esac; shift; doneif [[ "$1" == '--' ]]; then shift; fi
#Check for command’s resultif ping -c 1 google.com; thenecho "It appears you have a working internet connection"fi
Payam Borosan.Goodluck