Skip to content

Instantly share code, notes, and snippets.

@deven96
Last active March 19, 2021 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deven96/89814c7ef9aa1cccc80f963fed915db1 to your computer and use it in GitHub Desktop.
Save deven96/89814c7ef9aa1cccc80f963fed915db1 to your computer and use it in GitHub Desktop.
File handling utilities
#!/bin/bash
# replaces the $x variable
# e.g replaceVariable first_locked 7777 ~/.bashrc
# will replace any export first_locked=* with export first_locked=7777 directly in ~/.bashrc
# and then proceed to source the script if it is an rc file
function replaceVariableInFile {
sed -i -e "s/^export\ $1=.*/export\ $1=$2/g" $3
# matches .bashrc and .zshrc files
if [[ "$3" =~ .*"rc" ]]; then
source $3 && echo "Sourced $3 file"
fi
}
# check if a variable export is in a file
# e.g checkOrIncludeVariable lastActive ~/.bashrc
# will check if there is a line "export lastActive=..."
# if there is none it will append a line "export lastActive=0" and source the file
function checkOrIncludeVariable {
grep -q "^export\ $1=.*" $2 || echo "export $1=0" >> $2
source $2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment