diff options
Diffstat (limited to 'bash.md')
| -rw-r--r-- | bash.md | 91 |
1 files changed, 90 insertions, 1 deletions
@@ -14,7 +14,7 @@ Remove longest from start # e.g. ${FILEPATH##*/} # get only file name portion -%% - longst from end, # - shortest from start +%% - longest from end, # - shortest from start ## Control flow @@ -26,14 +26,27 @@ Loop over integers for i in `seq 10`; do echo $i; done +Loop over lines of file: + + while IFS= read -r line; do + echo "tester: $line" + done < "$1" + ## Conditionals * `-z`: is empty string * `-n`: non-empty string * `-f`: is regular file +* `-d`: is a directory * `$A == $B`: string equality, accepts globs * `$A != $B`: string inequality +### Numeric + +* `-eq`, `-ne`: equal, not equal +* `-gt`, `-lt`: greater than, less than +* `-ge`, `-le`: greater than or equal, less than or equal + ## Heredocs cat << EOF > file @@ -53,3 +66,79 @@ Don't interpolate variables: cat << 'EOF' > file bla bla EOF + +## Arrays + +Declaring indexed arrays: + + declare -a name + +Associative arrays: + + declare -A name + +Assignment: + + # Indexed + array=(foo bar "baz bom"...) + # Associative + array=([bla]=foo [ble]=bar...) + +All values: + + ${array[*]} # one word, elements separated with first character of $IFS + ${array[@]} # separate words when double quoted + +All keys: + + ${!array[*]} + ${!array[@]} + +So looping: + + # Over values + for x in "${array[@]}"; do ... + # Over keys (0-based indices for indexed) + for x in "${!array[@]}"; do ... + + +Array size: + + ${#array[@]} + +Slice: + + # n elements starting at index i + ${array[@]:i:n} + +## Commandline arguments + +* `$#`: number of arguments. + +## Getopts example + + while getopts 'a:b:c' flag; do + case "${flag}" in + a) do_something $OPTARG ;; + b) b_option=$OPTARG ;; + c) c_flag=1 ;; + *) error "Unexpected option ${flag}" ;; + esac + done + +### With positional arguments + +Positional arguments will have to be supplied after flag options (`command +[options] <args>`): + + shift $((OPTIND-1)) + + +## Shell optional behavior/settings/options (`shopt` builtin) + + # Enable + shopt -s <option> + # Disable + shopt -u <option> + +* `nocaseglob`: glob matching is case insensitive |