-2

I want to make a shell script that checks if an environment variable has been added, otherwise.

if [ ! echo $PATH | grep "/what_i_want_to_add" ]; then # If there is no environment variable
    export PATH=$PATH:/what_i_want_to_add
fi

If possible, I would like to discard the output using /dev/null.
what should i do?

AMATEUR_TOSS
  • 256
  • 5
  • 13
  • AMATEUR_TOSS Check https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash https://stackoverflow.com/questions/39296472/how-to-check-if-an-environment-variable-exists-and-get-its-value – axnet Jul 13 '20 at 10:36
  • 1
    `what should i do?` Read about test command in shell programming language. Read about `if` statement in shell programming language. Read about `grep` and how to use it and learn about `-q` option. Research word splitting, and why quoting of variables is needed. Use shellcheck.net to check comon mistakes – KamilCuk Jul 13 '20 at 10:53
  • @AMATEUR_TOSS : Please ask in an understandable way: The question title is about an environment variable to **exist**, and the question text is about an environment variable to be **added**. Also, you ask about how to discard output. This is a separate question; please don't ask two unrelated things in one question. Lastly the code you posted, has nothing to do with the **existence** of environment variables, but about their **contents**. – user1934428 Jul 13 '20 at 11:12
  • Note the `-q` option to grep. – William Pursell Jul 13 '20 at 11:27

1 Answers1

3

This is a function used on archlinux inside /etc/profile. It works flawlessly when adding path to PATH.

# Append our default paths
appendpath () {
    case ":$PATH:" in
        *:"$1":*)
            ;;
        *)
            PATH="${PATH:+$PATH:}$1"
    esac
}

# usage example:
appendpath '/what_i_want_to_add'
  • case ":$PATH:" in - match $PATH but with a trailing and leading colon, so that we can:
    • *:"$1":*) - match :$PATH: with anything, followed by a colon, followed by the argument, followed by colon, and anything. Because we used ":$PATH:" it will expand to :/path1:/path/2:/path/3: that can be matched against *:/path1:* with globbing expression.
      • If the match is successful, do nothing
    • *) - else
      • Add the argument to PATH.
      • ${PATH:+$PATH:} - A shell parameter expansion. If PATH is empty or NULL, then expand to nothing. If the path is not empty, then expand to $PATH followed by a colon. This can handle an empty PATH= argument so that leading empty : is not added.
KamilCuk
  • 120,984
  • 8
  • 59
  • 111