简体   繁体   中英

Why doesn't this xargs work?

I've been trying to get all of the value within a redis db, using redis-cli. This is done in principal by redis-cli keys "*" (returns all keys) and piping that to redis-cli get (returns the value of a key).

I've since discovered (on SO) a way to do it:

echo 'keys YOURKEY*' | redis-cli | sed 's/^/get /' | redis-cli

But before, I was trying this, and the get command never seemed to run. Am I doing xargs wrong?:

redis-cli keys "*" | xargs -0 -I % redis-cli get "%"

I appreciate that 'why didn't this work' questions are frowned upon, but I think the answer will be informative for people confused by xargs.

You're using the -0 flag to xargs , which says that your input items are terminated by a null character (ASCII 0) rather than whitespace. It is unlikely that the redis-cli command outputs keys in this format. In fact, it seems to produce output that has one key/line, like this:

# redis-cli keys "*"
_tooz_group:central-global
_tooz_beats:38225c46-7ed8-4c2a-b1eb-6400d0f99004
_tooz_beats:bea903f7-ab5d-4503-be19-f2029beece93
_tooz_beats:bd859c91-0245-45cf-a289-23fc25998e97
_tooz_beats:04528af5-dd97-41af-87a6-d7dc0c0d9f5d
_tooz_beats:974b9d9d-86ff-457e-9a5c-e857ec12a915
_tooz_beats:a55cfe65-f344-4ed4-9b9f-a0ace4d8f6d3

If you drop the -0 from your xargs invocation, it should work fine:

# redis-cli keys "*" | xargs -I% redis-cli get %

If you have keys containing whitespace, this won't work (because xargs expects your input data to be whitespace delimited). In that case, you can explicitly set the delimiter to \\n :

# redis-cli keys "*" | xargs --delimiter '\n' -I% redis-cli get %

I think you want this:

# Set some data
redis-cli set mb1 A
OK

# Set some more
redis-cli set mb2 B
OK

# Check the keys we have
redis-cli keys "mb*"
1) "mb1"
2) "mb2"


#Retrieve those puppies, passing one at a time with "-n 1"
redis-cli keys "mb*" | xargs -n 1 redis-cli get 
"A"
"B"

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