简体   繁体   中英

How do I check if a string containing variables is present in a specific file in bash?

Background

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:

  1. Check if the string (eg BASH_CONFIG or FISH_CONFIG ) is contained within each specified file
  2. If it isn't contained within the file, printf it into the designated file.
  3. If it is contained within the file, then do not add it again.

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.

Current Bash Script Snippet

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)"

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM