LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Parenthesis and other odd characters passed to bash function (https://www.linuxquestions.org/questions/programming-9/parenthesis-and-other-odd-characters-passed-to-bash-function-632543/)

jakeo25 04-02-2008 04:57 PM

Parenthesis and other odd characters passed to bash function
 
I would like to code a function which will accept a '(' in the parameter, and do some stream editing in the process. So for example:
------------------------------------------------------------------------
#!/bin/bash

function foo ()
{
# use the entire commandline ($@) as a single argument
## this allows spaces
output=`echo "$@" | sed 's|(|\\\(|g'`
echo $output
}

foo Hello (world)
-----------------------------------------------------------------------

If I do this, bash will complain about the '(' and ')'

output:

./foobar.sh: line 11: syntax error near unexpected token `('
./foobar.sh: line 11: `foo Hello (world)'

There are other characters, such as '*', which cause problems.

The way around this is to use double quotes in the call:

foo "Hello (world)"

output:

Hello \(world)

So my question is: How can I re-write foo() to avoid using the double quotes when I make the call?


Thanks in advance

Jake

colucix 04-02-2008 05:08 PM

Quote:

Originally Posted by jakeo25 (Post 3108705)
So my question is: How can I re-write foo() to avoid using the double quotes when I make the call?

You can't. The error is generated before the function can do anything (indeed the function is not called). Since parentheses have a special meaning in bash, you must escape them for literal interpretation. You can use double quotes, single quotes or the escape character. Anyway, what's wrong in using double quotes?

jakeo25 04-03-2008 10:27 AM

Thanks for the reply.


All times are GMT -5. The time now is 06:00 AM.