I am writing a script, there is a section where the script needs to fetch the server name and port detail from a reference file.

I have used the below logic to fetch the details, however I am looking for some better option. Please advise.

HOST=$(grep SERVER_NAME $HOME/env.ref | awk -F '=' '{print $2}')
PORT=$(grep SERVER_PORT $HOME/env.ref | awk -F '=' '{print $2}')

if [ "${HOST}" -a "{PORT}" ]
echo "Details extracted"
echo "Details not found"

2 Answers 2

  1. You don't need to pipe grep into awk. try this:

    HOST="$(awk -F= '/SERVER_NAME/ {print $2}' $HOME/env.ref)"
    PORT="$(awk -F= '/SERVER_PORT/ {print $2}' $HOME/env.ref)"
  2. if/then/else is more readable if you a) don't waste a line on then and b) indent the clauses. Also, you don't need to use {...} around variables unless there's a possibility of ambiguity. e.g. $HOSTPORT is a single variable called $HOSTPORT, while ${HOST}${PORT} is two variables concatenated without anything between them. Finally, you forgot the $ on $PORT.

    if [ "$HOST" -a "$PORT" ] ; then 
      echo "Details extracted"
      echo "Details not found"

    And if all you're going to do is just echo found or not found, it can be done on one line:

    [ "$HOST" -a "$PORT" ] && echo "Details extracted" || echo "Details not found"

There isn't much else in your script that could be improved much. There's just not enough there. Depending on exactly what the rest of your script is doing, it may be better to write the whole thing in awk or perl or python or something...but it's impossible to know without a description or large script sample.


Assuming the format of this file is name=value lines, you could do this in plain shell (bash or zsh):

while read -r line; do 
    case "$line" in 
        SERVER_NAME=*|SERVER_PORT=*) declare "$line";; 
done < env.ref

That reads the file, and when the specified lines are found, use the declare builtin to create the variables in this current shell (though when called inside a function, note that it would restrict the scope of that variable to that function (unless you use declare -g)).

  • Note that in bash, contrary to most other shells declare -g (typeset being more portable) is not to prevent the variable being declared local, but to change the type or value of the variable in the top-most scope, so declare -g may not do what you want if the variable was already declared local in an outer scope. bash -c 'a=1; f() { declare a=2; g; }; g() { declare -g a=3; echo "$a"; }; f' outputs 2, not 3 and the wrong variable is being modified. Jul 25, 2017 at 12:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .