Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm trying to better organise a bash script as part of a re-write/re-organisation and am wondering what "best practice" is in the following situation:

ymd=`echo "${NOEXT}" | egrep -o -m 1 "\-20[0-9]{2}\-[0-9]{2}\-[0-9]{2}\-"`

or

ymd=`egrep -o -m 1 "\-20[0-9]{2}\-[0-9]{2}\-[0-9]{2}\-" <<< ${NOEXT}` 

I believe the first version, due to the pipe, creates a subshell. Does the second version with the here string? I'm figuring it doesn't, but want to validate my assumptions.

share|improve this question

2 Answers 2

up vote 4 down vote accepted

The latter doesn't which you can (roughly) verify by looking (on an idle system) at the increase of the PIDs - when running the former, it will increase by 2, when running the latter, it will only increase by 1.

But, it's a Bashism, and maybe should be replaced with a here document:

ymd=`egrep -o -m 1 "\-20[0-9]{2}\-[0-9]{2}\-[0-9]{2}\-" <<EOF
${NOEXT}
EOF`
share|improve this answer
    
It doesn't need to be portable (in this case) so I'm ok with the here strings. Out of curiosity though, how would you replace the above with a here doc? Just the same as I'm doing with the relevant EOF etc? –  Josh Smeaton Feb 8 '13 at 12:40
    
Updated my answer. –  Stefan Seidel Feb 9 '13 at 20:14

If you can use bash and don't require POSIX compatibility, you can do the regular expression match without using the external call to egrep.

[[ $NOEXT =~ -20[0-9]{2}-[0-9]{2}-[0-9]{2}- ]]
ymd=${BASH_REMATCH[0]}
share|improve this answer
    
Yes, there are a couple of these I'm converting in exactly this way. But there are lots of echo | cut as well. –  Josh Smeaton Feb 8 '13 at 22:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.