简体   繁体   中英

Shell script substring extraction and manipulation

I was able to extract a substring from a string; but no matter what syntax changes I try (and I've tried many), I am unable to actually enter the if block in this snippet even though the print out suggests that the CLIENT_NAME string matches the expected one (attached the output from the first echo ). Only the first echo prints anything. What am I doing wrong here? Any ideas are really appreciated!

The idea is if the client is named say aa_NNNN , then I need to extract the aa and the NNNN and check if the aa matches a known string (say " xx ") and if it does, only then, calculate the version NNNN and do something if version NNNN exceeds a known version MMMM .

#! /bin/sh
CLIENT=$1
...
CLIENT_NAME="${CLIENT:0:2}"
CLIENT_VERSION=2015
echo "Before compare; client: $CLIENT_NAME; version: $CLIENT_VERSION"
if [ "$CLIENT_NAME" == "xx" ]; then
   CLIENT_VERSION="${CLIENT:3:4}"
   echo "Inside compare; client: $CLIENT_NAME; version: $CLIENT_VERSION"
   if [ $CLIENT_VERSION -ge 2016 ]; then
      ...
   fi
fi

First echo output:

Before compare; client: xx; version: 2015

/bin/sh --version returns:

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

I got the same result running your code, but removing the quotes from the substring extraction (and replacing the , with : in the second one) fixed it...

CLIENT_NAME=${CLIENT:0:2}

...and...

CLIENT_VERSION=${CLIENT:3:4}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM