1

I have a script like,

#/bin/bash -x
LASTBUILD=' 174254491  2018-08-08T11:04:40Z  gs://abc/kishor/5.4.0.61/xyz-5.4.0-61.tgz
 TOTAL: 46 objects, 7325896651 bytes (6.82 GiB)'

echo "this is the LASTBUILD ============== $LASTBUILD"

LATESTBUILD=echo $LASTBUILD | cut -d ' ' -f 3

echo "this is the LATESTBUILD ############### $LATESTBUILD"

After execution shows result as below,

[root@root ~]# echo $LATESTBUILD

[root@root ~]#

My expected result is as below,

[root@root ~]# echo $LATESTBUILD
gs://abc/kishor/5.4.0.61/xyz-5.4.0-61.tgz
[root@root ~]#

The above code is not working.

PS: Also tried using awk but not worked,

LATESTBUILD=$LASTBUILD | awk -F '/' '{print $5}'
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Hemant
  • 37
  • What output do you get from your script? I can already see that you're failing to use export so any variable set inside the script are not going to be recognized by the shell after the script exits... – Shadur-don't-feed-the-AI Aug 10 '18 at 06:50

4 Answers4

2
awk '{ print $3 }' <<< $LASTBUILD

The default field separator in awk in a space and so print the 3rd space delimited field.

1

There are a few issues with your script:

  1. Your hash bang is invalid. You have #/bin/bash -x and it should be #!/bin/bash -x
  2. Your LASTBUILD variable is weird. Each column is separated by double spaces which will cause cut to act oddly, and you also don't want a newline in it with cut.
  3. LATESTBUILD=echo $LASTBUILD | cut -d ' ' -f 3 is nothing. This should be in command substitution, but even then it wont work because of the double spacing. It should be: LATESTBUILD=$(cut -d ' ' -f5 <<<"$LASTBUILD")
  4. The variables set inside your script will not be available outside of it, so doing echo $LATESTBIULD on the command line after the script executes will not and should not work.

Here is a working version of your script:

#!/bin/bash

LASTBUILD='174254491   2018-08-08T11:04:40Z  gs://abc/kishor/5.4.0.61/xyz-5.4.0-61.tgz TOTAL: 46 objects, 7325896651 bytes (6.82 GiB)'

echo "this is the LASTBUILD ============== $LASTBUILD"

LATESTBUILD=$(cut -d ' ' -f5 <<<"$LASTBUILD")

echo "this is the LATESTBUILD ############### $LATESTBUILD"
jesse_b
  • 37,005
1

You could do it (carefully) with the shell:

LASTBUILD=' 174254491  2018-08-08T11:04:40Z  gs://abc/kishor/5.4.0.61/xyz-5.4.0-61.tgz TOTAL: 46 objects, 7325896651 bytes (6.82 GiB)'
set -f               # disable filename generation (globbing)
set -- $LASTBUILD    # specifically un-quoted, to allow splitting
LATESTBUILD=$3
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
0

How about

read _ _ LATESTBUILD _ <<< $LASTBUILD
RudiC
  • 8,969
  • you'd also want to disable filename generation with set -f, just in case there were any wildcards in the contents of the variable. – Jeff Schaller Aug 09 '18 at 14:09