Skip to content

Instantly share code, notes, and snippets.

@kongchen
Last active January 3, 2023 09:29
Show Gist options
  • Select an option

  • Save kongchen/6748525 to your computer and use it in GitHub Desktop.

Select an option

Save kongchen/6748525 to your computer and use it in GitHub Desktop.
set properties file value by key via bash shell
#!/bin/bash
############################
#script function
############################
setProperty(){
awk -v pat="^$1=" -v value="$1=$2" '{ if ($0 ~ pat) print value; else print $0; }' $3 > $3.tmp
mv $3.tmp $3
}
############################
### usage: setProperty $key $value $filename
setProperty "store.folder" "/opt/current/store" "env.properties"
@Kolyall
Copy link
Copy Markdown

Kolyall commented Apr 3, 2020

@iyerusad Thanks, also can you add a func for add new variable?

@iyerusad
Copy link
Copy Markdown

iyerusad commented Apr 3, 2020

@iyerusad Thanks, also can you add a func for add new variable?

You can call "newvar=somevalue" >> file.txt to append new string to file. But no, not updating at this time.

@dktsudgg
Copy link
Copy Markdown

cat << 'EOF' > /usr/local/bin/setProperty

#!/bin/bash
#version: 0.2
### usage: setProperty key value filename

if [ -z "$1" ]; then
  echo "No parameters provided, exiting..."
  exit 1
fi
if [ -z "$2" ]; then
  echo "Key provided, but no value, breaking"
  exit 1
fi
if [ -z "$3" ] && [ -z "$setPropertyFile" ]; then
  echo "No file provided or setPropertyFile is not set, exiting..."
  exit 1
fi

if [ "$setPropertyFile" ] && [ "$3" ]; then
    echo "setPropertyFile variable is set AND filename in comamnd! Use only or the other. Exiting..."
    exit 1
else
  if [ "$3" ] && [ ! -f "$3" ]; then
    echo "File in command NOT FOUND!"
    exit 1
  elif [ "$setPropertyFile" ] && [ ! -f "$setPropertyFile" ]; then
    echo "File in setPropertyFile variable NOT FOUND!"
    exit 1
  fi
fi

if [ "$setPropertyFile" ]; then
  file=$setPropertyFile
else
  file=$3
fi

is_already_exist=`cat $file | grep $1 | cut -d'=' -f2`
if [ "$is_already_exist" ]; then
  awk -v pat="^$1=" -v value="$1=$2" '{ if ($0 ~ pat) print value; else print $0; }' "$file" > "$file".tmp
else
  cat $file > "$file".tmp
  echo "$1=$2" >> "$file".tmp
fi
mv "$file".tmp "$file"

EOF

chmod +x /usr/local/bin/setProperty

I've modified your script to reflect the requirements mentioned above
@iyerusad @Kolyall

@gopisettypradeep
Copy link
Copy Markdown

Can you explain about the scripts with details

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment