João
João

Reputation: 187

After running shell script, variables lose their value

I have done a simple shell script:

#!/bin/sh
file_name=$1
state=`cat "$file_name" | grep "port protocol" | awk '{print $4}'`
echo $state
reason=`cat "$file_name" | grep "port protocol"`
echo $reason

This outputs the values $state and $reason. However, when I run..

echo $state

..in the console it does not output nothing. It seems like the variable loses its value. Is this the normal behaviour or should I had something to the script?

Thanks!

Upvotes: 1

Views: 792

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74695

Assuming that you're running your script like ./script.sh or sh script.sh, then this is the expected behaviour. Child processes cannot change the environment of their parent. The fact that you're running a shell script from a shell doesn't change this rule.

What you can do is source the script instead of executing it, to set those variables in the local environment:

. script.sh

This effectively runs the lines of the script in your current shell, so the variables will be set there.

While I've got your attention, I'd recommend making the following changes to your script:

#!/bin/sh
file_name=$1
state=$(awk '/port protocol/ {print $4}' "$file_name")
echo "$state"
reason=$(grep "port protocol" "$file_name")
echo "$reason"

In short, quote your variables, avoid useless calls to cat and use pattern matching in awk rather than piping grep to it.

Upvotes: 2

Related Questions