3

I've got a a bash script with two functions, one is the main function which includes a case command, that case command will then call a second function and pass a specific argument.

In the second function I have a command that works on the command line, but when run as part of the bash script I get the following error:

: line 57: syntax error near unexpected token `('
: line 57: `           local DATE=`echo $URL|sed -r 's/.*____([0-9]{1,2})_([0-9]{1,2})_([0-9]{1,2}).*/20\3-\1-\2/;s/-([0-9]{1})-/-0\1-/;s/-([0-9]{1})$/-0\1/'`'

the function is,

dlshow ()
{
    local URL=$1
    echo "URL: "$URL
    local DATE=`echo $URL|sed -r 's/.*____([0-9]{1,2})_([0-9]{1,2})_([0-9]{1,2}).*/20\3-\1-\2/;s/-([0-9]{1})-/-0\1-/;s/-([0-9]{1})$/-0\1/'`

I can't figure out why as a bash command I get the error.

chepner
  • 497,756
  • 71
  • 530
  • 681
tincanfury
  • 63
  • 3
  • 9

1 Answers1

0

Try this:

echo $URL | sed -e '...' |  { read DATE ; ... ; }
ceving
  • 21,900
  • 13
  • 104
  • 178
  • I don't see why the evaluation of the sed script should fail, and your statement regarding the quotes and backticks is false. – user2719058 Nov 08 '13 at 23:36
  • @user2719058 I have removed the statement. But avoiding backticks is always a good idea: http://stackoverflow.com/questions/4708549/shell-programming-whats-the-difference-between-command-and-command – ceving Nov 09 '13 at 09:42
  • Unfortunately, doing so will assign `DATE` inside the subshell defined by the pipe, and not globally. Fix this with a command substitution as so: `{ read DATE ; ... ; } < <(echo $URL | sed -e '...')`. – gniourf_gniourf Nov 09 '13 at 10:11
  • @gniourf_gniourf: that's just tossing around the command list inbetween the curlies, isn't it? – user2719058 Nov 09 '13 at 14:29
  • @user2719058 it is, but it will make `DATE` available in subsequent commands. – gniourf_gniourf Nov 09 '13 at 14:32
  • @gniourf_gniourf Ah sorry, I got confused by the curlies; of course you're right. Although I would then simply drop the curlies and attach the redirection to the `read` builtin alone. – user2719058 Nov 09 '13 at 14:35
  • @user2719058 I have no ideas what your final goal is.. so I just took the command (with grouping) given here and adapted it. I'm not even sure the `read` is mandatory: `DATE=$(echo $URL | sed -e '...')` might be enough. – gniourf_gniourf Nov 09 '13 at 14:36
  • @user2719058 Btw you can remove the pipe and the `echo`: `sed -e '...' <<<$URL` – ceving Nov 09 '13 at 20:45
  • I'll have to look at how { read DATE ; ... ; } works, that's a new method to me. user2719058: googled that, did not know about here strings, good to know! thanks! problem answered in the above response, thanks for all the info! – tincanfury Nov 23 '13 at 17:02
  • Please explain why the backticks cause the problem. – Spidey Jul 04 '17 at 17:07