DEV Community

Ryan Ju
Ryan Ju

Posted on

Bash Notes

Case Convertion

# Convert snake/kebab case to upper camel.  MacOS and Linux.
> echo 'snake_or-kebab-case' | sed -E 's/(-|_)/ /g' | awk '{for (i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) substr($i,2)} 1' | sed -E 's/ //g')"
# output: 
SnakeOrKebabCase

Color output

color_some_output_light_blue() {
  while read line; do
    # If line has substring "environment"
    if [[ "$line" == *environment* ]]; then
      # Light blue color
      printf '\e[1;34m%s\e[m\n' "$line"
    else
      echo "$line"
    fi
  done
}

cat file | color_some_output_light_blue

Arrays

Create array from lines with spaces

# If you have file like this
cat file
# output:
foo bar
baz 
qux

# This doesn't work, because it breaks at both space and new line
arr=($(cat file))
printf "%s;%s;%s\n" "${arr[@]}"
# output:
foo;bar;baz

# This works
declare -a arr
while IFS='' read -r line; do
  var+=("$(line)") # Note the quotes
done <<<"$(cat file)"
printf "%s;%s;%s\n" "${arr[@]}"
# output:
foo bar;baz;qux

Top comments (0)