4

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.

2 Answers 2

4

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`
2
  • 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? Feb 8, 2013 at 12:40
  • Updated my answer. Feb 9, 2013 at 20:14
2

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]}
1
  • Yes, there are a couple of these I'm converting in exactly this way. But there are lots of echo | cut as well. Feb 8, 2013 at 22:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .