Re: bash (sh?) scripting question



On 2006-09-06, Leonardo wrote:
Hi,

I am trying to implement a type of "try" function, that will execute a
command and verify the exit code:

try()
{
eval $*

To maintain the argumnts are they are received, use "$@":

eval "$@"

if [ $? -ne 0 ]; then
echo "failed"
exit $?

At this point, $? contains the result of the echo command.

fi
}

I wish to send it a command like this:

SOMEFILE="/some path/with spaces"
mv "$SOMEFILE" "$SOMEFILE.backup"

But the quotes are causing a problem:

try "mv \"$SOMEFILE\" \"$SOMEFILE.bak\""
try mv "$SOMEFILE" "$SOMEFILE.backup"

Both of these last 2 lines fail.
I used this to see how parameters were passed:

try
{
for param in $*

for param in "$@"

do
echo "Param: $param"
done
}

it showed that in the last case, despite putting quotes around the variable
name, it ends up being split everwhere there are spaces.

This is weird and I don't know how to solve it.

try()
{
eval "$@"
_TRY=$?
if [ $_TRY -ne 0 ]; then
echo "failed"
exit $_TRY
fi
}


--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
.



Relevant Pages

  • Re: Shell Script to Remove Old Files
    ... Note it needs a TSM server: ... # Verify command line arguments ... echo "\nError: $STARTDIR does not exist.\n" ...
    (comp.unix.admin)
  • Re: Errors returned by System()function
    ... specified command succesfully and /that/ command ... For example ('echo $?' ... Seems that bash exits with a exit code of 1 when it can't find the ... php$ wget http://www.baddomain.net/index.html ...
    (comp.lang.php)
  • Re: bash (sh?) scripting question
    ... I am trying to implement a type of "try" function, that will execute a command and verify the exit code: ... trap 'echo failed' ERR ... echo "Param: $param" ...
    (comp.unix.shell)
  • bash (sh?) scripting question
    ... command and verify the exit code: ... I wish to send it a command like this: ... echo "Param: $param" ...
    (comp.unix.shell)
  • Re: Batch file
    ... You can use the "exit" command in a batch file if you ... @echo off ...
    (microsoft.public.win2000.general)