Reputation: 741
I have two files:
~/.bash.local # $LOCAL_BASH_CONFIG_FILE
~/.fish.local # $LOCAL_FISH_CONFIG_FILE
I am dynamically adding configurations to each file within a bash script. Each file is parsed by either ~/.bash_profile
if it's for bash
or ~/.config/fish/config.fish
if it's for fish
. to implement these configurations.
However, I do not want to add the lines that configure a binary to either file every time I run my bash script. I would like it to do the following:
BASH_CONFIG
or FISH_CONFIG
) is contained within each specified fileprintf
it into the designated file. My below script's purpose is to install the npm
package n
using n-install and add the proper configuration to both bash
and fish
.
execute
is a function that I defined to run the task in the background and display a message on the screen with a spinner.
add_n_configs() {
# bash
declare -r BASH_CONFIGS="
# n - Node version management.
export N_PREFIX=\"\$HOME/n\";
[[ :\$PATH: == *\":\$N_PREFIX/bin:\"* ]] || PATH+=\":\$N_PREFIX/bin\"
"
execute \
"printf '%s\n' '$BASH_CONFIGS' >> $LOCAL_BASH_CONFIG_FILE \
&& . $LOCAL_BASH_CONFIG_FILE" \
"n (update $LOCAL_BASH_CONFIG_FILE)"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# fish
declare -r FISH_CONFIGS="
# n - Node version management.
set -xU N_PREFIX \"\$HOME/n\"
set -U fish_user_paths \"\$N_PREFIX/bin\" \$fish_user_paths
"
execute \
"printf '%s\n' '$FISH_CONFIGS' >> $LOCAL_FISH_CONFIG_FILE" \
"n (update $LOCAL_FISH_CONFIG_FILE)"
}
Upvotes: 0
Views: 151
Reputation: 741
After a bit of research it seems that this task can be accomplished using grep
as so:
if ! grep -q "$BASH_CONFIGS" "$LOCAL_BASH_CONFIG_FILE"; then
execute \
"printf '%s\n' '$BASH_CONFIGS' >> $LOCAL_BASH_CONFIG_FILE \
&& . $LOCAL_BASH_CONFIG_FILE" \
"n (update $LOCAL_BASH_CONFIG_FILE)"
fi
if ! grep -q "$FISH_CONFIGS" "$LOCAL_FISH_CONFIG_FILE"; then
execute \
"printf '%s\n' '$FISH_CONFIGS' >> $LOCAL_FISH_CONFIG_FILE" \
"n (update $LOCAL_FISH_CONFIG_FILE)"
fi
grep
is a command-line utility that can search and filter text using a common regular expression syntax.
To search for an exact string: grep search_string path/to/file
To search for an exact string in quiet mode: grep -q search_string path/to/file
grep -q
will only search a file until a match has been found.Upvotes: 1