Use shebang interpreter

#!/bin/bash

Variable

variable="value"
output=$(command)
echo $variable

Need to use $ to reference the variable, it it’s empty it will print nothing.

  • it’s best to create variable in a shell script in lower case since system environment variables are declared in upper case
    $() capture the output of a command
  • create a command in the background and grab the output
  • by default with variable, that variable will be executed as a command
myvar="echo hello world"
$myvar # hello world will be echoed

When declaring a variable in terminal, it will be removed on next login.

List
1 2 3 4 5 each item is separated by space
{1..5} will create a list, similar to python range function, but both numbers are inclusive

Math

expr 1 + 1 in bash need to use expr to evaluate a expression

  • there need to be space between number and operator
  • for multiplication need to use \* to escape the asterix
  • expr only work with integer argument/variables
    Arithmetic operations
    $(( 1 + 1 )) surround the operation with double bracket and $
  • + - * ** / % integer operation only
  • () BEDMAS
    bc calculator
    echo '1+1' | bc need to echo to stdout and pipe it into bc
  • + - * / ^ % only integer exponent is supported
  • () BEDMAS
  • echo 'scale=2; 4/6' | bc scale determine the number of decimal places, followed by semi-colon
  • bc -l by default will create many decimal places
  • echo 'sqrt(25)' | bc only square root possible