1758992 Members
3755 Online
108878 Solutions
New Discussion юеВ

Re: simple script

 
SOLVED
Go to solution
Darrell Allen
Honored Contributor

simple script

Hi all,

This is driving me crazy (short trip). Here's a simple script:

if [ "$DISPLAY" ]
then
echo DISPLAY $DISPLAY
else
term=`tty | cut -c6-`
export DISPLAY=`who -u | grep "$term " | awk '{print $1}'`":0.0"
fi

It seems the script runs fine in a subshell (./script) but I know I have to run it in my current shell (. ./script) to get the desired result. Here's the problem:

When I run ". ./script" it fails with:
sh: DISPLAY: Parameter not set.

It doesn't matter if my shell is specified in /etc/passwd as /sbin/sh, /usr/bin/sh, or /usr/bin/ksh. I get the error regardless.

Another oddity is that if I simply go into another shell after logging in, the script then works as desired. Again, it doesn't matter which of the 3 shells I choose.

Thanks for helping,
Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)
4 REPLIES 4
David Lodge
Trusted Contributor
Solution

Re: simple script

This is one of the differences between an interactive shell and a shell script.

Your .profile is sourced into your login (ie interactive) shell environment (ie not run as a shell script) which has the -u flag set to error on unknown variables. To see:

$ print $wibble
sh: wibble: Parameter not set.
$ set +u
$ print $wibble

$

So to get round it either:
1) Set a variable before you use it. (Remember that even in quotes if a variable doesn't exist the shell *still* looks at it)
2) Use set +u like above, don't forget to unset it afterwards.
3) Use the shell construct:
variable=${variable:-NOTSET}
(which states if variable is unset set it to NOTSET otherwise set it to the contents of variable)

I'd advise using 3, this is a very good safety measure to use in any shell script!

One other thing to remember is the difference between a non-existant variable and a blank one. eg:
$ echo $fred
sh: fred: Parameter not set.
$ fred=
$ echo $fred

$

dave
Darrell Allen
Honored Contributor

Re: simple script

Excellent Dave!

I added "set +u" at the beginning of my script.

Why would I want to use "set -u" anyway?

Thanks,
Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)
David Lodge
Trusted Contributor

Re: simple script

It's intended as a safety measure for shell users in case of a mistake, so that an error is returned instead of just going ahead and treating the variable like a blank string, eg:

rm -rf /${ADIR}
mv /${ADIR} /tmp/backup

imagine if you executed on of the above without ADIR set or accidently mistyped it as SDIR and pressed return without noticing?

dave
Darrell Allen
Honored Contributor

Re: simple script

Of course. With +u "cd ${ADIR}" returns 0 even if ${ADIR} doesn't exist (the cd takes you to your home dir). Not a good thing.

Guess I wasn't thinking (what else is new).

Thanks,
Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)