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="somethinglong"
substr="thing"if [ !"${name/$substr/}"="$name" ] ;thenecho"'$substr' found in '$name'"elseecho"'$substr' not found in '$name'"fi
Arrays
Length
a=(1 2 3 4)
echo${#a[@]}
Associative Arrays
declare -A my_dict
my_dict[foo]=bar
my_dict[some]=thing
my_dict[one]=two
forkeyin"${!my_dict[@]}";doprintf"key $key value ${my_dict[$key]}\n"done
Input
Read a line of input
You almost always want to use read -r rather than just read.
read -r COMPLEX_STRING
printf"$COMPLEX_STRING\n"
Read line by line, in the current shell
If you pipe a command directly to a while read ... loop, it will spawn a new subshell which cannot interact
with the parent shell (for example, to change global variables).
GLOBAL_VAL=1
printf"line1\nline2\nline3\n"|whileread -r LINE ;do
GLOBAL_VAL=$(($GLOBAL_VAL+1))doneecho$GLOBAL_VAL
This will print 1.
To loop in the current shell, read from the pipe using file descriptor redirection.
GLOBAL_VAL=1
whileread -r LINE ;do
GLOBAL_VAL=$(($GLOBAL_VAL+1))done<<(printf"line1\nline2\nline3\n")echo$GLOBAL_VAL
This will print 4.
Output
Printing output lines
Using echo is usually not what you want:
It can fail if first argument ends up starting with "-".
Not all echos support the -e or -n option.
Usually you want to use printf.
To print the literal string "foo\nbar":
printf"%s""foo\nbar"
To print the string and change "\n" into a newline character: