Bash datatypes

From wikinotes
Revision as of 13:40, 17 July 2021 by Will (talk | contribs) (→‎basics)

Defaults

VAR=${var:=DEFAULT}  # $var unless undefined, then 'DEFAULT'

strings

basics

firstname="luke"
lastname="skywalker"

fullname="$firstname $lastname"   # variables are expanded within '"' quotes.

# HEREDOC format
vimrc=$(cat <<-EOF
filetype off
syntax enable
set rtp+=.
EOF
)

substitution

var="hello:how:are:you"
var=${var//:/*}
echo $var

#> hello*how*are*you

slices

var="abcd"

# echo ${var:<start>:<finish>}
echo ${var:1}              #> bcd
echo ${var:0:3}            #> abc
echo ${var:0:${#var[@]}}   #> abcd

IFS

The $IFS variable (internal field separator) determines which character is used to separate items in a list. By default it is a single empty space.

You can change it, if you'd like. Some use cases:

  • iterating over stdout lines
  • iterating over $PATH entries
export PATH=/sbin:/bin:/usr/bin:/usr/local/bin
oIFS="$IFS"
IFS=":"

for item in ${PATH[@]}; do
    echo "$item"
done

IFS="$oIFS"  # restore IFS to default

numbers

arrays

basics

NOTE:

Arrays are 1-indexed

array=()                    # initialize empty array
array=(one two three)       # create array
array=(\
  one \
  two \
  three \
)
array+=(four)                    # append to array

array[2]="two"                   # assign array val (NOTE no dollar)
${#array[@]}                     # array length
${array[3:6]}                    # array of items 3-6
${array[*]}                      # all array entries
array=( "${array[@]/$delete}" )  # delete item from array

joined=$(printf ",%s" "${array[@]}" | cut -c 2-)  # join array by ','

concat=( 
    "${array_1[@]}"
    "${array_2[@]}"
)

[[ "${array[@]}" =~ "two" ]] && echo "two in array"  # check item in array

array from output

file_array=( $(ls -l | tr '\n' ' ') )  # save multiline output to array (one entry per line)