Last active
January 3, 2023 09:29
-
-
Save kongchen/6748525 to your computer and use it in GitHub Desktop.
set properties file value by key via bash shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" |
setprop.sh Worked perfectly Thank you!
Thank's a lot!
@iyerusad Thanks, also can you add a func for add new variable?
@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.
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
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
A horrid "enhancement":
Usage:
or