1834343 Members
2069 Online
110066 Solutions
New Discussion

Re: ksh question

 
SOLVED
Go to solution
Sean OB_1
Honored Contributor

ksh question

Hello!

What is the easiest way in ksh to get the results of a command into a variable?

For example I want to issue a umount of a directory. I know I can interogate the return code to see if it's successful.

However I want to grab the output if it's unsucessful to help determine why.

For example if you umount a directory that isn't mounted you get this result:


-> umount /tmp/sean2343234

umount: cannot find /tmp/sean2343234 in /etc/mnttab
cannot unmount /tmp/sean2343234


While a failure because it is in use gives:

-> umount /tmp
umount: cannot unmount /tmp : Device busy



I need to take different actions based on why it failed so I need to catch the results of the command.

This is fairly urgent as I have to have this script in production on Saturday.

TIA,

Sean
7 REPLIES 7
James R. Ferguson
Acclaimed Contributor

Re: ksh question

Hi Sean:

Since well-behaved commands write errors to stderr:

# umount /cdrom 2> /tmp/error.$$

...and then if you wanted to put the contents of /tmp/error.$$ into a variable, do:

# ERRTXT=`
Regards!

...JRF...
Patrick Wallek
Honored Contributor

Re: ksh question

What about something like this

umount /tmp/sean2343234 2> /umount.err
error=$(cat /umount.err)

The first statement will redirect standard error to /umount.err and the second will assign the contents of /umount.err to the variable error.
Chris Wilshaw
Honored Contributor

Re: ksh question

You could try

export UMERR=`umount /tmp 2>&1`

This will set the value of UMERR to the output of the command.

The only problem that I can think of with this is that it joins all the output into a single line.
S.K. Chan
Honored Contributor

Re: ksh question

I usually send the std error output to a file and examine the file later in the script if needed.
..
ERRORLOG=/tmp/myerror.log
..
umount /tmp 2>$ERRORLOG
..
Tony Contratto
Respected Contributor
Solution

Re: ksh question

Hi Sean,

One way to do it:

VAR=$(/usr/sbin/umount /mount/point 2>&1)

--
Tony
got root?
Sridhar Bhaskarla
Honored Contributor

Re: ksh question

Hi Sean,

I would do the following.

umount $mount_poing > /tmp/umount$$ > /dev/null 2>&1

grep "Device busy" /tmp/umount$$ > /dev/null 2>&1

if [ $? = 0 ]
then
your_busy_action
else
if
Grep "cannot find" /tmp/umount$$ > /dev/null 2>&1

if [ $? = 0 ]
then
your_mnttab_action
fi
fi
fi

etc.,

Some of the commands exit with appropriate exit codes. For ex., "useradd". It will be much easier to deal with them. So a simple case statement can effectively cover them.

But for comands like mount, we will have to do something like the above.

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Sean OB_1
Honored Contributor

Re: ksh question

This is what I wanted to do:

VAR=$(/usr/sbin/umount /mount/point 2>&1)


I was trying this and couldn't get the syntax right.

Thanks much!