Skip to content

Instantly share code, notes, and snippets.

@vikyd
Last active September 12, 2018 03:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikyd/4acd26dcf42e44a4c8db1514ffb78a10 to your computer and use it in GitHub Desktop.
Save vikyd/4acd26dcf42e44a4c8db1514ffb78a10 to your computer and use it in GitHub Desktop.
Shell: get value from key=value file with value trim and key trim, and allow `=` ` space` in value
#!/bin/sh
# These vars and func are used to get value from a key=value file
# It will also trim the leading and trailing whitespace, tab
# Key with space after or before is supported
getVal(){
# cut `=` in val: https://unix.stackexchange.com/a/53315/207518
# grep: allow space after or before of key
# awk trim space after and before of value: https://unix.stackexchange.com/a/205854/207518
declare val=$(cat ${1} | grep "^ *${2} *=" | cut -d '=' -f 2- | awk '{$1=$1}1')
# eval: https://unix.stackexchange.com/a/250178/207518
eval ${3}=\$val
}
# Example
getVal keyval.txt key01 myVal
echo "|$val|"
echo "|$myVal|"
abc=123
akey01=4563456
key01 = adsfadf 234 sfda @#$% sdafa;][34d= dsf asdf k-= 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment