开发者

Bash script - Take system output and use it as a variable

Pretty simple question, I'm trying to get some output after executing a command and use it again.

#!/bin/bash
echo what's the source db name?
read SOURCE
echo what's the target db name?
read TARGET
db2 backup db $SOURCE online compress include logs
READ SOME OF THIS LINE = SOURCE
db2 restore database $SOURCE taken at $DB2TIME into $TARGET

the line "READ SOME OF THIS LINE" outputs like this: Backup successful. The timestamp for this backup image is : 20100906142221 开发者_如何学JAVAI think a grep command would do it, but I'm not 100% sure


Continuing with @pax's answer, your code now becomes:

#!/bin/bash
echo what's the source db name?
read SOURCE
echo what's the target db name?
read TARGET
DB2TIME=$(db2 backup db $SOURCE online compress include logs)
# you have read it above <--- READ SOME OF THIS LINE = SOURCE
db2 restore database $SOURCE taken at $DB2TIME into $TARGET


@pax @dennis @pavanlimo Sorry I made a typo when I was writing this,

I need to be able to read $DB2TIME after I execute:

db2 backup db $SOURCE online compress include logs

I get the output:

The timestamp for this backup image is : 20100906142221

I need to turn the 20100906142221 into $DB2TIME so I can execute the next command

db2 restore database $SOURCE taken at $DB2TIME into $TARGET


In bash, you capture the output of a command with $() (or backticks, but I prefer the former since you can nest them):

pax> xx=$(ls -1 | grep bac)

pax> echo "..${xx}.."
..backup0.sh
backup1.sh..

So, in your particular case you'd be looking at something like:

timestamp=$(db2 backup db $SOURCE online compress include logs 2>&1
    | tee /tmp/output
    | grep 'image is'
    | awk '{print $11}')

Keep in mind I've split that across multiple lines for readability but it should go on a single line. As to how it works:

  • The 2>&1 combines standard output and error.
  • The tee will ensure you have the entire output stored somewhere.
  • The grep will give you the relevant line.
  • The awk will print out only 20100906142221.
  • The xx=$(...) will take that and assign it to xx.

You may need to fine-tune some of the command if your output is slightly different to what you've stated but that should be a good start.


Based on comments, here's what you need to start with:

#!/bin/bash
echo what's the source db name?
read SOURCE
echo what's the target db name?
read TARGET
db2 backup db $SOURCE online compress include logs 2>&1 | tee /tmp/db_bkp_$$
DB2TIME=$(cat /tmp/db_bkp_$$ | grep 'image is' | awk '{print $11}')
rm -rf /tmp/db_bkp_$$
db2 restore database $SOURCE taken at $DB2TIME into $TARGET

This will execute the DB2 command sending output and error to both the terminal and the temporary file ($$ gives you the current process ID to avoid file name collisions). You then extract the date/time from the temporary file then delete that file.

Then you use the date/time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜