{
  "schema_version": 2,
  "id": "develop/tools/cli",
  "title": "Redis CLI",
  "url": "https://redis.io/docs/latest/develop/tools/cli/",
  "summary": "Overview of redis-cli, the Redis command line interface",
  "aliases": [
    "/develop/connect/cli",
    "/connect/cli/",
    "/manual/cli/"
  ],
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-09-11T15:49:15+01:00",
  "page_type": "content",
  "content_hash": "e439d052a972c3d5104869b779774f95222015dd74b27589bdcf603c93b31c86",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "In interactive mode, `redis-cli` has basic line editing capabilities to provide a familiar typing experience.\n\nTo launch the program in special modes, you can use several options, including:\n\n* Simulate a replica and print the replication stream it receives from the primary.\n* Check the latency of a Redis server and display statistics. \n* Request ASCII-art spectrogram of latency samples and frequencies.\n\nThis topic covers the different aspects of `redis-cli`, starting from the simplest and ending with the more advanced features."
    },
    {
      "id": "install-redis-cli",
      "title": "Install `redis-cli`",
      "role": "setup",
      "text": "You have several options for installing or using `redis-cli`. The easiest method is to install the standalone `redis-cli` binary for Linux or macOS. See the [Install redis-cli](https://redis.io/docs/latest/operate/oss_and_stack/install/install-stack/install-redis-cli) page for more information.\n\nOther methods include:\n\n- [Install Redis Open Source](https://redis.io/docs/latest/operate/oss_and_stack/install/install-stack). The `redis-cli` utility is installed as part of each installation method.\n- [Build Redis from source](https://redis.io/docs/latest/operate/oss_and_stack/install/build-stack). Instead of building everything, you can just run the following command:\n\n    `$ make redis-cli`.\n    \n    The `redis-cli` utility will be built in the `/path/to/redis-source/src` directory as `/path/to/redis-source/src/redis-cli`.\n\nIf you prefer not to install Redis, you can also run `redis-cli` in Docker. See the [Run `redis-cli` using Docker](https://redis.io/docs/latest/operate/oss_and_stack/install/install-stack/docker#connect-with-redis-cli) page for instructions."
    },
    {
      "id": "command-line-usage",
      "title": "Command line usage",
      "role": "syntax",
      "text": "To run a Redis command and return a standard output at the terminal, include the command to execute as separate arguments of `redis-cli`:\n\n    $ redis-cli INCR mycounter\n    (integer) 7\n\nThe reply of the command is \"7\". Since Redis replies are typed (strings, arrays, integers, nil, errors, etc.), you see the type of the reply between parentheses. This additional information may not be ideal when the output of `redis-cli` must be used as input of another command or redirected into a file.\n\n`redis-cli` only shows additional information for human readability when it detects the standard output is a tty, or terminal. For all other outputs it will auto-enable the *raw output mode*, as in the following example:\n\n    $ redis-cli INCR mycounter > /tmp/output.txt\n    $ cat /tmp/output.txt\n    8\n\nNote that `(integer)` is omitted from the output because `redis-cli` detects\nthe output is no longer written to the terminal. You can force raw output\neven on the terminal with the `--raw` option:\n\n    $ redis-cli --raw INCR mycounter\n    9\n\nYou can force human readable output when writing to a file or in\npipe to other commands by using `--no-raw`.\n\nFor complete command line usage, see [below](#usage)."
    },
    {
      "id": "string-quoting-and-escaping",
      "title": "String quoting and escaping",
      "role": "content",
      "text": "When `redis-cli` parses a command, whitespace characters automatically delimit the arguments.\nIn interactive mode, a newline sends the command for parsing and execution.\nTo input string values that contain whitespaces or non-printable characters, you can use quoted and escaped strings.\n\nQuoted string values are enclosed in double (`\"`) or single (`'`) quotation marks.\nEscape sequences are used to put nonprintable characters in character and string literals.\n\nAn escape sequence contains a backslash (`\\`) symbol followed by one of the escape sequence characters.\n\nDoubly-quoted strings support the following escape sequences:\n\n* `\\\"` - double-quote\n* `\\n` - newline\n* `\\r` - carriage return\n* `\\t` - horizontal tab\n* `\\b` - backspace\n* `\\a` - alert\n* `\\\\` - backslash\n* `\\xhh` - any ASCII character represented by a hexadecimal number (_hh_)\n\nSingle quotes assume the string is literal, and allow only the following escape sequences:\n* `\\'` - single quote\n* `\\\\` - backslash\n\nFor example, to return `Hello World` on two lines:\n\n[code example]\n\nWhen you input strings that contain single or double quotes, as you might in passwords, for example, escape the string, like so: \n\n[code example]"
    },
    {
      "id": "host-port-password-and-database",
      "title": "Host, port, password, and database",
      "role": "content",
      "text": "By default, `redis-cli` connects to the server at the address 127.0.0.1 with port 6379.\nYou can change the port using several command line options. To specify a different host name or an IP address, use the `-h` option. In order to set a different port, use `-p`.\n\n    $ redis-cli -h redis15.localnet.org -p 6390 PING\n    PONG\n\nIf your instance is password protected, the `-a <password>` option will\nperform authentication saving the need of explicitly using the [`AUTH`](https://redis.io/docs/latest/commands/auth) command:\n\n    $ redis-cli -a myUnguessablePazzzzzword123 PING\n    PONG\n\n**NOTE:** For security reasons, provide the password to `redis-cli` automatically via the\n`REDISCLI_AUTH` environment variable.\n\nFinally, it's possible to send a command that operates on a database number\nother than the default number zero by using the `-n <dbnum>` option:\n\n    $ redis-cli FLUSHALL\n    OK\n    $ redis-cli -n 1 INCR a\n    (integer) 1\n    $ redis-cli -n 1 INCR a\n    (integer) 2\n    $ redis-cli -n 2 INCR a\n    (integer) 1\n\nSome or all of this information can also be provided by using the `-u <uri>`\noption and the URI pattern `redis://user:password@host:port/dbnum`:\n\n    $ redis-cli -u redis://LJenkins:p%40ssw0rd@redis-16379.hosted.com:16379/0 PING\n    PONG\n\n**NOTE:**\nUser, password and dbnum are optional.\nFor authentication without a username, use username `default`.\nFor TLS, use the scheme `rediss`.\n\nYou can use the `-4` or `-6` argument to set a preference for IPv4 or IPv6, respectively, for DNS lookups."
    },
    {
      "id": "ssltls",
      "title": "SSL/TLS",
      "role": "content",
      "text": "By default, `redis-cli` uses a plain TCP connection to connect to Redis.\nYou may enable SSL/TLS using the `--tls` option, along with `--cacert` or\n`--cacertdir` to configure a trusted root certificate bundle or directory.\n\nIf the target server requires authentication using a client side certificate,\nyou can specify a certificate and a corresponding private key using `--cert` and\n`--key`."
    },
    {
      "id": "get-input-from-other-programs",
      "title": "Get input from other programs",
      "role": "content",
      "text": "There are two ways you can use `redis-cli` in order to receive input from other\ncommands via the standard input. One is to use the target payload as the last argument\nfrom *stdin*. For example, in order to set the Redis key `net_services`\nto the content of the file `/etc/services` from a local file system, use the `-x`\noption:\n\n    $ redis-cli -x SET net_services < /etc/services\n    OK\n    $ redis-cli GETRANGE net_services 0 50\n    \"#\\n# Network services, Internet style\\n#\\n# Note that \"\n\nIn the first line of the above session, `redis-cli` was executed with the `-x` option and a file was redirected to the CLI's\nstandard input as the value to satisfy the `SET net_services` command phrase. This is useful for scripting.\n\nA different approach is to feed `redis-cli` a sequence of commands written in a\ntext file:\n\n    $ cat /tmp/commands.txt\n    SET item:3374 100\n    INCR item:3374\n    APPEND item:3374 xxx\n    GET item:3374\n    $ cat /tmp/commands.txt | redis-cli\n    OK\n    (integer) 101\n    (integer) 6\n    \"101xxx\"\n\nAll the commands in `commands.txt` are executed consecutively by\n`redis-cli` as if they were typed by the user in interactive mode. Strings can be\nquoted inside the file if needed, so that it's possible to have single\narguments with spaces, newlines, or other special characters:\n\n    $ cat /tmp/commands.txt\n    SET arg_example \"This is a single argument\"\n    STRLEN arg_example\n    $ cat /tmp/commands.txt | redis-cli\n    OK\n    (integer) 25"
    },
    {
      "id": "continuously-run-the-same-command",
      "title": "Continuously run the same command",
      "role": "content",
      "text": "It is possible to execute a single command a specified number of times\nwith a user-selected pause between executions. This is useful in\ndifferent contexts - for example when we want to continuously monitor some\nkey content or [`INFO`](https://redis.io/docs/latest/commands/info) field output, or when we want to simulate some\nrecurring write event, such as pushing a new item into a list every 5 seconds.\n\nThis feature is controlled by two options: `-r <count>` and `-i <delay>`.\nThe `-r` option states how many times to run a command and `-i` sets\nthe delay between the different command calls in seconds (with the ability\nto specify values such as 0.1 to represent 100 milliseconds).\n\nBy default the interval (or delay) is set to 0, so commands are just executed\nASAP:\n\n    $ redis-cli -r 5 INCR counter_value\n    (integer) 1\n    (integer) 2\n    (integer) 3\n    (integer) 4\n    (integer) 5\n\nTo run the same command indefinitely, use `-1` as the count value.\nTo monitor over time the RSS memory size it's possible to use the following command:\n\n    $ redis-cli -r -1 -i 1 INFO | grep rss_human\n    used_memory_rss_human:2.71M\n    used_memory_rss_human:2.73M\n    used_memory_rss_human:2.73M\n    used_memory_rss_human:2.73M\n    ... a new line will be printed each second ..."
    },
    {
      "id": "mass-insertion-of-data-using-redis-cli",
      "title": "Mass insertion of data using `redis-cli`",
      "role": "content",
      "text": "Mass insertion using `redis-cli` is covered in a separate page as it is a\nworthwhile topic itself. Please refer to our [mass insertion guide](https://redis.io/docs/latest/develop/clients/patterns/bulk-loading)."
    },
    {
      "id": "csv-output",
      "title": "CSV output",
      "role": "content",
      "text": "A CSV (Comma Separated Values) output feature exists within `redis-cli` to export data from Redis to an external program.  \n\n    $ redis-cli LPUSH mylist a b c d\n    (integer) 4\n    $ redis-cli --csv LRANGE mylist 0 -1\n    \"d\",\"c\",\"b\",\"a\"\n\nNote that the `--csv` flag will only work on a single command, not the entirety of a DB as an export."
    },
    {
      "id": "run-lua-scripts",
      "title": "Run Lua scripts",
      "role": "content",
      "text": "The `redis-cli` has extensive support for using the debugging facility\nof Lua scripting, available with Redis 3.2 onwards. For this feature, refer to the [Redis Lua debugger documentation](https://redis.io/docs/latest/develop/programmability/lua-debugging).\n\nEven without using the debugger, `redis-cli` can be used to\nrun scripts from a file as an argument:\n\n    $ cat /tmp/script.lua\n    return redis.call('SET',KEYS[1],ARGV[1])\n    $ redis-cli --eval /tmp/script.lua location:hastings:temp , 23\n    OK\n\nThe Redis [`EVAL`](https://redis.io/docs/latest/commands/eval) command takes the list of keys the script uses, and the\nother non key arguments, as different arrays. When calling [`EVAL`](https://redis.io/docs/latest/commands/eval) you\nprovide the number of keys as a number. \n\nWhen calling `redis-cli` with the `--eval` option above, there is no need to specify the number of keys\nexplicitly. Instead it uses the convention of separating keys and arguments\nwith a comma. This is why in the above call you see `location:hastings:temp , 23` as arguments.\n\nSo `location:hastings:temp` will populate the [`KEYS`](https://redis.io/docs/latest/commands/keys) array, and `23` the `ARGV` array.\n\nThe `--eval` option is useful when writing simple scripts. For more\ncomplex work, the Lua debugger is recommended. It is possible to mix the two approaches, since the debugger can also execute scripts from an external file."
    },
    {
      "id": "interactive-mode",
      "title": "Interactive mode",
      "role": "content",
      "text": "We have explored how to use the Redis CLI as a command line program.\nThis is useful for scripts and certain types of testing, however most\npeople will spend the majority of time in `redis-cli` using its interactive\nmode.\n\nIn interactive mode the user types Redis commands at the prompt. The command\nis sent to the server, processed, and the reply is parsed back and rendered\ninto a simpler form to read.\n\nNothing special is needed for running the `redis-cli` in interactive mode -\njust execute it without any arguments\n\n    $ redis-cli\n    127.0.0.1:6379> PING\n    PONG\n\nThe string `127.0.0.1:6379>` is the prompt. It displays the connected Redis server instance's hostname and port.\n\nThe prompt updates as the connected server changes or when operating on a database different from the database number zero:\n\n    127.0.0.1:6379> SELECT 2\n    OK\n    127.0.0.1:6379[2]> DBSIZE\n    (integer) 1\n    127.0.0.1:6379[2]> SELECT 0\n    OK\n    127.0.0.1:6379> DBSIZE\n    (integer) 503"
    },
    {
      "id": "handle-connections-and-reconnections",
      "title": "Handle connections and reconnections",
      "role": "content",
      "text": "Using the `CONNECT` command in interactive mode makes it possible to connect\nto a different instance, by specifying the *hostname* and *port* we want\nto connect to:\n\n    127.0.0.1:6379> CONNECT metal 6379\n    metal:6379> PING\n    PONG\n\nAs you can see the prompt changes accordingly when connecting to a different server instance.\nIf a connection is attempted to an instance that is unreachable, the `redis-cli` goes into disconnected\nmode and attempts to reconnect with each new command:\n\n    127.0.0.1:6379> CONNECT 127.0.0.1 9999\n    Could not connect to Redis at 127.0.0.1:9999: Connection refused\n    not connected> PING\n    Could not connect to Redis at 127.0.0.1:9999: Connection refused\n    not connected> PING\n    Could not connect to Redis at 127.0.0.1:9999: Connection refused\n\nGenerally after a disconnection is detected, `redis-cli` always attempts to\nreconnect transparently; if the attempt fails, it shows the error and\nenters the disconnected state. The following is an example of disconnection\nand reconnection:\n\n    127.0.0.1:6379> INFO SERVER\n    Could not connect to Redis at 127.0.0.1:6379: Connection refused\n    not connected> PING\n    PONG\n    127.0.0.1:6379> \n    (now we are connected again)\n\nWhen a reconnection is performed, `redis-cli` automatically re-selects the\nlast database number selected. However, all other states about the\nconnection is lost, such as within a MULTI/EXEC transaction:\n\n    $ redis-cli\n    127.0.0.1:6379> MULTI\n    OK\n    127.0.0.1:6379> PING\n    QUEUED\n\n    ( here the server is manually restarted )\n\n    127.0.0.1:6379> EXEC\n    (error) ERR EXEC without MULTI\n\nThis is usually not an issue when using the `redis-cli` in interactive mode for\ntesting, but this limitation should be known.\n\nUse the `-t <timeout>` option to specify server timeout in seconds."
    },
    {
      "id": "editing-history-completion-and-hints",
      "title": "Editing, history, completion and hints",
      "role": "content",
      "text": "Because `redis-cli` uses the\n[linenoise line editing library](http://github.com/antirez/linenoise), it\nalways has line editing capabilities, without depending on `libreadline` or\nother optional libraries.\n\nCommand execution history can be accessed in order to avoid retyping commands by pressing the arrow keys (up and down).\nThe history is preserved between restarts of the CLI, in a file named\n`.rediscli_history` inside the user home directory, as specified\nby the `HOME` environment variable. It is possible to use a different\nhistory filename by setting the `REDISCLI_HISTFILE` environment variable,\nand disable it by setting it to `/dev/null`.\n\nThe `redis-cli` client is also able to perform command-name completion by pressing the TAB\nkey, as in the following example:\n\n    127.0.0.1:6379> Z<TAB>\n    127.0.0.1:6379> ZADD<TAB>\n    127.0.0.1:6379> ZCARD<TAB>\n\nOnce Redis command name has been entered at the prompt, the `redis-cli` will display\nsyntax hints. Like command history, this behavior can be turned on and off via the `redis-cli` preferences.\n\nReverse history searches, such as `CTRL-R` in terminals, is supported.\n\nStarting with Redis 8.8, `redis-cli` supports word-jump navigation (`Alt/Option + ←/→`, `Ctrl + ←/→`), which makes\nediting long commands much more efficient."
    },
    {
      "id": "preferences",
      "title": "Preferences",
      "role": "content",
      "text": "There are two ways to customize `redis-cli` behavior. The file `.redisclirc`\nin the home directory is loaded by the CLI on startup. You can override the\nfile's default location by setting the `REDISCLI_RCFILE` environment variable to\nan alternative path. Preferences can also be set during a CLI session, in which \ncase they will last only the duration of the session.\n\nTo set preferences, use the special `:set` command. The following preferences\ncan be set, either by typing the command in the CLI or adding it to the\n`.redisclirc` file:\n\n* `:set hints` - enables syntax hints\n* `:set nohints` - disables syntax hints"
    },
    {
      "id": "run-the-same-command-n-times",
      "title": "Run the same command N times",
      "role": "content",
      "text": "It is possible to run the same command multiple times in interactive mode by prefixing the command\nname by a number:\n\n    127.0.0.1:6379> 5 INCR mycounter\n    (integer) 1\n    (integer) 2\n    (integer) 3\n    (integer) 4\n    (integer) 5"
    },
    {
      "id": "show-online-help-for-redis-commands",
      "title": "Show online help for Redis commands",
      "role": "content",
      "text": "`redis-cli` provides online help for most Redis [commands](/commands), using the `HELP` command. The command can be used\nin two forms:\n\n* `HELP @<category>` shows all the commands about a given category. The\ncategories are: \n    - `@generic`\n    - `@string`\n    - `@list`\n    - `@set`\n    - `@sorted_set`\n    - `@hash`\n    - `@pubsub`\n    - `@transactions`\n    - `@connection`\n    - `@server`\n    - `@scripting`\n    - `@hyperloglog`\n    - `@cluster`\n    - `@geo`\n    - `@stream`\n* `HELP <commandname>` shows specific help for the command given as argument.\n\nFor example in order to show help for the [`PFADD`](https://redis.io/docs/latest/commands/pfadd) command, use:\n\n    127.0.0.1:6379> HELP PFADD\n\n    PFADD key element [element ...]\n    summary: Adds the specified elements to the specified HyperLogLog.\n    since: 2.8.9\n\nNote that `HELP` supports TAB completion as well."
    },
    {
      "id": "clear-the-terminal-screen",
      "title": "Clear the terminal screen",
      "role": "content",
      "text": "Using the `CLEAR` command in interactive mode clears the terminal's screen."
    },
    {
      "id": "special-modes-of-operation",
      "title": "Special modes of operation",
      "role": "content",
      "text": "So far we saw two main modes of `redis-cli`.\n\n* Command line execution of Redis commands.\n* Interactive \"REPL\" usage.\n\nThe CLI performs other auxiliary tasks related to Redis that\nare explained in the next sections:\n\n* Monitoring tool to show continuous stats about a Redis server.\n* Scanning a Redis database for very large keys.\n* Key space scanner with pattern matching.\n* Acting as a [Pub/Sub](https://redis.io/docs/latest/develop/pubsub) client to subscribe to channels.\n* Monitoring the commands executed into a Redis instance.\n* Checking the [latency](https://redis.io/docs/latest/operate/oss_and_stack/management/optimization/latency) of a Redis server in different ways.\n* Checking the scheduler latency of the local computer.\n* Transferring RDB backups from a remote Redis server locally.\n* Acting as a Redis replica for showing what a replica receives.\n* Simulating [LRU](https://redis.io/docs/latest/develop/reference/eviction) workloads for showing stats about keys hits.\n* A client for the Lua debugger."
    },
    {
      "id": "continuous-stats-mode",
      "title": "Continuous stats mode",
      "role": "content",
      "text": "Continuous stats mode is probably one of the lesser known yet very useful features of `redis-cli` to monitor Redis instances in real time. To enable this mode, the `--stat` option is used.\nThe output is very clear about the behavior of the CLI in this mode:\n\n    $ redis-cli --stat\n    ------- data ------ --------------------- load -------------------- - child -\n    keys       mem      clients blocked requests            connections\n    506        1015.00K 1       0       24 (+0)             7\n    506        1015.00K 1       0       25 (+1)             7\n    506        3.40M    51      0       60461 (+60436)      57\n    506        3.40M    51      0       146425 (+85964)     107\n    507        3.40M    51      0       233844 (+87419)     157\n    507        3.40M    51      0       321715 (+87871)     207\n    508        3.40M    51      0       408642 (+86927)     257\n    508        3.40M    51      0       497038 (+88396)     257\n\nIn this mode a new line is printed every second with useful information and differences of request values between old data points. Memory usage, client connection counts, and various other statistics about the connected Redis database can be easily understood with this auxiliary `redis-cli` tool.\n\nThe `-i <interval>` option in this case works as a modifier in order to\nchange the frequency at which new lines are emitted. The default is one\nsecond."
    },
    {
      "id": "scan-for-big-keys-and-memory-usage",
      "title": "Scan for big keys and memory usage",
      "role": "content",
      "text": ""
    },
    {
      "id": "big-keys",
      "title": "Big keys",
      "role": "content",
      "text": "In this special mode, `redis-cli` works as a key space analyzer. It scans the\ndataset for big keys, but also provides information about the data types\nthat the data set consists of. This mode is enabled with the `--bigkeys` option,\nand produces verbose output:\n\n    $ redis-cli --bigkeys\n\n    # Scanning the entire keyspace to find biggest keys as well as\n    # average sizes per key type.  You can use -i 0.1 to sleep 0.1 sec\n    # per 100 SCAN commands (not usually needed).\n\n    100.00% ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n    Keys sampled: 55\n\n    -------- summary -------\n\n    Total key length in bytes is 495 (avg len 9.00)\n    ... output truncated for AI-facing Markdown ...\n    1 hashs with 3 fields (01.82% of keys, avg size 3.00)\n    3 streams with 8 entries (05.45% of keys, avg size 2.67)\n    2 TDIS-TYPEs with 0 ? (03.64% of keys, avg size 0.00)\n    1 TopK-TYPEs with 0 ? (01.82% of keys, avg size 0.00)\n    2 sets with 5 members (03.64% of keys, avg size 2.50)\n    1 CMSk-TYPEs with 0 ? (01.82% of keys, avg size 0.00)\n    2 zsets with 11 members (03.64% of keys, avg size 5.50)\n    25 ReJSON-RLs with 0 ? (45.45% of keys, avg size 0.00)\n\nIn the first part of the output, each new key larger than the previous larger\nkey (of the same type) encountered is reported. The summary section\nprovides general stats about the data inside the Redis instance.\n\nThe program uses the [`SCAN`](https://redis.io/docs/latest/commands/scan) command, so it can be executed against a busy\nserver without impacting the operations, however the `-i` option can be\nused in order to throttle the scanning process of the specified fraction\nof second for each [`SCAN`](https://redis.io/docs/latest/commands/scan) command. \n\nFor example, `-i 0.01` will slow down the program execution considerably, but will also reduce the load on the server\nto a negligible amount.\n\nNote that the summary also reports in a cleaner form the biggest keys found\nfor each time. The initial output is just to provide some interesting info\nASAP if running against a very large data set.\n\nThe `--bigkeys` option now works on cluster replicas."
    },
    {
      "id": "memory-usage",
      "title": "Memory usage",
      "role": "content",
      "text": "Similar to the `--bigkeys` option, `--memkeys` allows you to scan the entire keyspace to find biggest keys as well as\nthe average sizes per key type.\n\n    $ redis-cli --memkeys\n\n    # Scanning the entire keyspace to find biggest keys as well as\n    # average sizes per key type.  You can use -i 0.1 to sleep 0.1 sec\n    # per 100 SCAN commands (not usually needed).\n\n    100.00% ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n    Keys sampled: 55\n\n    -------- summary -------\n\n    Total key length in bytes is 495 (avg len 9.00)\n    ... output truncated for AI-facing Markdown ...\n    1 hashs with 104 bytes (01.82% of keys, avg size 104.00)\n    3 streams with 16960 bytes (05.45% of keys, avg size 5653.33)\n    2 TDIS-TYPEs with 19648 bytes (03.64% of keys, avg size 9824.00)\n    1 TopK-TYPEs with 114256 bytes (01.82% of keys, avg size 114256.00)\n    2 sets with 208 bytes (03.64% of keys, avg size 104.00)\n    1 CMSk-TYPEs with 144056 bytes (01.82% of keys, avg size 144056.00)\n    2 zsets with 304 bytes (03.64% of keys, avg size 152.00)\n    25 ReJSON-RLs with 15748 bytes (45.45% of keys, avg size 629.92)\n\nThe `--memkeys` option now works on cluster replicas."
    },
    {
      "id": "combine---bigkeys-and---memkeys",
      "title": "Combine `--bigkeys` and `--memkeys`",
      "role": "content",
      "text": "You can use the `--keystats` and `--keystats-samples` options to combine `--memkeys` and `--bigkeys` with additional distribution data.\n\n    $ redis-cli --keystats\n\n    # Scanning the entire keyspace to find the biggest keys and distribution information.\n    # Use -i 0.1 to sleep 0.1 sec per 100 SCAN commands (not usually needed).\n    # Use --cursor <n> to start the scan at the cursor <n> (usually after a Ctrl-C).\n    # Use --top <n> to display <n> top key sizes (default is 10).\n    # Ctrl-C to stop the scan.\n\n    100.00% ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n    Keys sampled: 55\n    Keys size:    1.30M\n\n    --- Top 10 key sizes ---\n      1    1.00M MBbloomCF  \"bikes:models\"\n    ... output truncated for AI-facing Markdown ...\n    --------- ------------ ------- -------- -------- ------------------ -----------\n    list                 1   1.82%     104B     104B            1 items        1.00\n    string              16  29.09%    1.33K      85B               149B          9B\n    MBbloomCF            1   1.82%    1.00M    1.00M                 -           - \n    hash                 1   1.82%     104B     104B           3 fields        3.00\n    stream               3   5.45%   16.56K    5.52K          8 entries        2.67\n    TDIS-TYPE            2   3.64%   19.19K    9.59K                 -           - \n    TopK-TYPE            1   1.82%  111.58K  111.58K                 -           - \n    set                  2   3.64%     208B     104B          5 members        2.50\n    CMSk-TYPE            1   1.82%  140.68K  140.68K                 -           - \n    zset                 2   3.64%     304B     152B         11 members        5.50\n    ReJSON-RL           25  45.45%   15.38K     629B                 -           -"
    },
    {
      "id": "get-a-list-of-keys",
      "title": "Get a list of keys",
      "role": "content",
      "text": "It is also possible to scan the key space, again in a way that does not\nblock the Redis server (which does happen when you use a command\nlike `KEYS *`), and print all the key names, or filter them for specific\npatterns. This mode, like the `--bigkeys` option, uses the [`SCAN`](https://redis.io/docs/latest/commands/scan) command,\nso keys may be reported multiple times if the dataset is changing, but no\nkey would ever be missing, if that key was present since the start of the\niteration. Because of the command that it uses this option is called `--scan`.\n\n    $ redis-cli --scan | head -10\n    key-419\n    key-71\n    key-236\n    key-50\n    key-38\n    key-458\n    key-453\n    key-499\n    key-446\n    key-371\n\nNote that `head -10` is used in order to print only the first ten lines of the\noutput.\n\nScanning is able to use the underlying pattern matching capability of\nthe [`SCAN`](https://redis.io/docs/latest/commands/scan) command with the `--pattern` option.\n\n    $ redis-cli --scan --pattern '*-11*'\n    key-114\n    key-117\n    key-118\n    key-113\n    key-115\n    key-112\n    key-119\n    key-11\n    key-111\n    key-110\n    key-116\n\nPiping the output through the `wc` command can be used to count specific\nkind of objects, by key name:\n\n    $ redis-cli --scan --pattern 'user:*' | wc -l\n    3829433\n\nYou can use `-i 0.01` to add a delay between calls to the [`SCAN`](https://redis.io/docs/latest/commands/scan) command.\nThis will make the command slower but will significantly reduce load on the server."
    },
    {
      "id": "pubsub-mode",
      "title": "Pub/sub mode",
      "role": "content",
      "text": "The CLI is able to publish messages in Redis Pub/Sub channels using\nthe [`PUBLISH`](https://redis.io/docs/latest/commands/publish) command. Subscribing to channels in order to receive\nmessages is different - the terminal is blocked and waits for\nmessages, so this is implemented as a special mode in `redis-cli`. Unlike\nother special modes this mode is not enabled by using a special option,\nbut simply by using the [`SUBSCRIBE`](https://redis.io/docs/latest/commands/subscribe) or [`PSUBSCRIBE`](https://redis.io/docs/latest/commands/psubscribe) command, which are available in\ninteractive or command mode:\n\n    $ redis-cli PSUBSCRIBE '*'\n    Reading messages... (press Ctrl-C to quit)\n    1) \"PSUBSCRIBE\"\n    2) \"*\"\n    3) (integer) 1\n\nThe *reading messages* message shows that we entered Pub/Sub mode.\nWhen another client publishes some message in some channel, such as with the command `redis-cli PUBLISH mychannel mymessage`, the CLI in Pub/Sub mode will show something such as:\n\n    1) \"pmessage\"\n    2) \"*\"\n    3) \"mychannel\"\n    4) \"mymessage\"\n\nThis is very useful for debugging Pub/Sub issues.\nTo exit the Pub/Sub mode just process `CTRL-C`."
    },
    {
      "id": "monitor-commands-executed-in-redis",
      "title": "Monitor commands executed in Redis",
      "role": "content",
      "text": "Similarly to the Pub/Sub mode, the monitoring mode is entered automatically\nonce you use the [`MONITOR`](https://redis.io/docs/latest/commands/monitor) command. All commands received by the active Redis instance will be printed to the standard output:\n\n    $ redis-cli MONITOR\n    OK\n    1460100081.165665 [0 127.0.0.1:51706] \"set\" \"shipment:8000736522714:status\" \"sorting\"\n    1460100083.053365 [0 127.0.0.1:51707] \"get\" \"shipment:8000736522714:status\"\n\nNote that it is possible to pipe the output, so you can monitor\nfor specific patterns using tools such as `grep`."
    },
    {
      "id": "monitor-the-latency-of-redis-instances",
      "title": "Monitor the latency of Redis instances",
      "role": "content",
      "text": "Redis is often used in contexts where latency is very critical. Latency\ninvolves multiple moving parts within the application, from the client library\nto the network stack, to the Redis instance itself.\n\nThe `redis-cli` has multiple facilities for studying the latency of a Redis\ninstance and understanding the latency's maximum, average and distribution.\n\nThe basic latency-checking tool is the `--latency` option. Using this\noption the CLI runs a loop where the [`PING`](https://redis.io/docs/latest/commands/ping) command is sent to the Redis\ninstance and the time to receive a reply is measured. This happens 100\ntimes per second, and stats are updated in a real time in the console:\n\n    $ redis-cli --latency\n    min: 0, max: 1, avg: 0.19 (427 samples)\n\nThe stats are provided in milliseconds. Usually, the average latency of\na very fast instance tends to be overestimated a bit because of the\nlatency due to the kernel scheduler of the system running `redis-cli`\nitself, so the average latency of 0.19 above may easily be 0.01 or less.\nHowever this is usually not a big problem, since most developers are interested in\nevents of a few milliseconds or more.\n\nSometimes it is useful to study how the maximum and average latencies\nevolve during time. The `--latency-history` option is used for that\npurpose: it works exactly like `--latency`, but every 15 seconds (by\ndefault) a new sampling session is started from scratch:\n\n    $ redis-cli --latency-history\n    min: 0, max: 1, avg: 0.14 (1314 samples) -- 15.01 seconds range\n    min: 0, max: 1, avg: 0.18 (1299 samples) -- 15.00 seconds range\n    min: 0, max: 1, avg: 0.20 (113 samples)^C\n\nSampling sessions' length can be changed with the `-i <interval>` option.\n\nThe most advanced latency study tool, but also the most complex to\ninterpret for non-experienced users, is the ability to use color terminals\nto show a spectrum of latencies. You'll see a colored output that indicates the\ndifferent percentages of samples, and different ASCII characters that indicate\ndifferent latency figures. This mode is enabled using the `--latency-dist`\noption:\n\n    $ redis-cli --latency-dist\n    (output not displayed, requires a color terminal, try it!)\n\nThere is another pretty unusual latency tool implemented inside `redis-cli`.\nIt does not check the latency of a Redis instance, but the latency of the\ncomputer running `redis-cli`. This latency is intrinsic to the kernel scheduler, \nthe hypervisor in case of virtualized instances, and so forth.\n\nRedis calls it *intrinsic latency* because it's mostly opaque to the programmer.\nIf the Redis instance has high latency regardless of all the obvious things\nthat may be the source cause, it's worth to check what's the best your system\ncan do by running `redis-cli` in this special mode directly in the system you\nare running Redis servers on.\n\nBy measuring the intrinsic latency, you know that this is the baseline,\nand Redis cannot outdo your system. In order to run the CLI\nin this mode, use the `--intrinsic-latency <test-time>`. Note that the test time is in seconds and dictates how long the test should run.\n\n    $ ./redis-cli --intrinsic-latency 5\n    Max latency so far: 1 microseconds.\n    Max latency so far: 7 microseconds.\n    Max latency so far: 9 microseconds.\n    Max latency so far: 11 microseconds.\n    Max latency so far: 13 microseconds.\n    Max latency so far: 15 microseconds.\n    Max latency so far: 34 microseconds.\n    Max latency so far: 82 microseconds.\n    Max latency so far: 586 microseconds.\n    Max latency so far: 739 microseconds.\n\n    65433042 total runs (avg latency: 0.0764 microseconds / 764.14 nanoseconds per run).\n    Worst run took 9671x longer than the average latency.\n\nIMPORTANT: this command must be executed on the computer that runs the Redis server instance, not on a different host. It does not connect to a Redis instance and performs the test locally.\n\nIn the above case, the system cannot do better than 739 microseconds of worst\ncase latency, so one can expect certain queries to occasionally run less than 1 millisecond."
    },
    {
      "id": "remote-backups-of-rdb-files",
      "title": "Remote backups of RDB files",
      "role": "content",
      "text": "During a Redis replication's first synchronization, the primary and the replica\nexchange the whole data set in the form of an RDB file. This feature is exploited\nby `redis-cli` in order to provide a remote backup facility that allows a\ntransfer of an RDB file from any Redis instance to the local computer running\n`redis-cli`. To use this mode, call the CLI with the `--rdb <dest-filename>`\noption:\n\n    $ redis-cli --rdb /tmp/dump.rdb\n    SYNC sent to master, writing 13256 bytes to '/tmp/dump.rdb'\n    Transfer finished with success.\n\nThis is a simple but effective way to ensure disaster recovery\nRDB backups exist of your Redis instance. When using this options in\nscripts or `cron` jobs, make sure to check the return value of the command.\nIf it is non zero, an error occurred as in the following example:\n\n    $ redis-cli --rdb /tmp/dump.rdb\n    SYNC with master failed: -ERR Can't SYNC while not connected with my master\n    $ echo $?\n    1"
    },
    {
      "id": "replica-mode",
      "title": "Replica mode",
      "role": "content",
      "text": "The replica mode of the CLI is an advanced feature useful for\nRedis developers and for debugging operations.\nIt allows for the inspection of the content a primary sends to its replicas in the replication\nstream in order to propagate the writes to its replicas. The option\nname is simply `--replica`. The following is a working example:\n\n    $ redis-cli --replica\n    SYNC with master, discarding 13256 bytes of bulk transfer...\n    SYNC done. Logging commands from master.\n    \"PING\"\n    \"SELECT\",\"0\"\n    \"SET\",\"last_name\",\"Enigk\"\n    \"PING\"\n    \"INCR\",\"mycounter\"\n\nThe command begins by discarding the RDB file of the first synchronization\nand then logs each command received in CSV format.\n\nIf you think some of the commands are not replicated correctly in your replicas\nthis is a good way to check what's happening, and also useful information\nin order to improve the bug report."
    },
    {
      "id": "perform-an-lru-simulation",
      "title": "Perform an LRU simulation",
      "role": "content",
      "text": "Redis is often used as a cache with [LRU eviction](https://redis.io/docs/latest/develop/reference/eviction).\nDepending on the number of keys and the amount of memory allocated for the\ncache (specified via the `maxmemory` directive), the amount of cache hits\nand misses will change. Sometimes, simulating the rate of hits is very\nuseful to correctly provision your cache.\n\nThe `redis-cli` has a special mode where it performs a simulation of GET and SET\noperations, using an 80-20% power law distribution in the requests pattern.\nThis means that 20% of keys will be requested 80% of times, which is a\ncommon distribution in caching scenarios.\n\nTheoretically, given the distribution of the requests and the Redis memory\noverhead, it should be possible to compute the hit rate analytically\nwith a mathematical formula. However, Redis can be configured with\ndifferent LRU settings (number of samples) and LRU's implementation, which\nis approximated in Redis, changes a lot between different versions. Similarly\nthe amount of memory per key may change between versions. That is why this\ntool was built: its main motivation was for testing the quality of Redis' LRU\nimplementation, but now is also useful for testing how a given version\nbehaves with the settings originally intended for deployment.\n\nTo use this mode, specify the amount of keys in the test and configure a sensible `maxmemory` setting as a first attempt.\n\nIMPORTANT NOTE: Configuring the `maxmemory` setting in the Redis configuration\nis crucial: if there is no cap to the maximum memory usage, the hit will\neventually be 100% since all the keys can be stored in memory. If too many keys are specified with maximum memory, eventually all of the computer RAM will be used. It is also needed to configure an appropriate\n*maxmemory policy*; most of the time `allkeys-lru` is selected.\n\nIn the following example there is a configured a memory limit of 100MB and an LRU\nsimulation using 10 million keys.\n\nWARNING: the test uses pipelining and will stress the server, don't use it\nwith production instances.\n\n    $ ./redis-cli --lru-test 10000000\n    156000 Gets/sec | Hits: 4552 (2.92%) | Misses: 151448 (97.08%)\n    153750 Gets/sec | Hits: 12906 (8.39%) | Misses: 140844 (91.61%)\n    159250 Gets/sec | Hits: 21811 (13.70%) | Misses: 137439 (86.30%)\n    151000 Gets/sec | Hits: 27615 (18.29%) | Misses: 123385 (81.71%)\n    145000 Gets/sec | Hits: 32791 (22.61%) | Misses: 112209 (77.39%)\n    157750 Gets/sec | Hits: 42178 (26.74%) | Misses: 115572 (73.26%)\n    154500 Gets/sec | Hits: 47418 (30.69%) | Misses: 107082 (69.31%)\n    151250 Gets/sec | Hits: 51636 (34.14%) | Misses: 99614 (65.86%)\n\nThe program shows stats every second. In the first seconds the cache starts to be populated. The misses rate later stabilizes into the actual figure that can be expected:\n\n    120750 Gets/sec | Hits: 48774 (40.39%) | Misses: 71976 (59.61%)\n    122500 Gets/sec | Hits: 49052 (40.04%) | Misses: 73448 (59.96%)\n    127000 Gets/sec | Hits: 50870 (40.06%) | Misses: 76130 (59.94%)\n    124250 Gets/sec | Hits: 50147 (40.36%) | Misses: 74103 (59.64%)\n\nA miss rate of 59% may not be acceptable for certain use cases;\n100MB of memory is not enough. Observe an example using a half gigabyte of memory. After several\nminutes the output stabilizes to the following figures:\n\n    140000 Gets/sec | Hits: 135376 (96.70%) | Misses: 4624 (3.30%)\n    141250 Gets/sec | Hits: 136523 (96.65%) | Misses: 4727 (3.35%)\n    140250 Gets/sec | Hits: 135457 (96.58%) | Misses: 4793 (3.42%)\n    140500 Gets/sec | Hits: 135947 (96.76%) | Misses: 4553 (3.24%)\n\nWith 500MB there is sufficient space for the key quantity (10 million) and distribution (80-20 style)."
    },
    {
      "id": "usage",
      "title": "Usage",
      "role": "syntax",
      "text": "[code example]\n\nOptions:\n\n- `-h <hostname>`: Server hostname (default: 127.0.0.1).\n- `-p <port>`: Server port (default: 6379).\n- `-t <timeout>`: Server connection timeout in seconds (decimals allowed). Default timeout is 0, meaning no limit, depending on the OS.\n- `-s <socket>`: Server socket (overrides hostname and port).\n- `-a <password>`: Password to use when connecting to the server. You can also use the REDISCLI_AUTH environment variable to pass this password more safely (if both are used, this argument takes precedence).\n- `--user <username>`: Used to send ACL style 'AUTH username pass'. Needs -a.\n- `--pass <password>`: Alias of -a for consistency with the new --user option.\n- `--askpass`: Force user to input password with mask from STDIN. If this argument is used, '-a' and REDISCLI_AUTH environment variable will be ignored.\n- `-u <uri>`: Server URI on format redis://user:password@host:port/dbnum User, password and dbnum are optional. For authentication without a username, use username 'default'. For TLS, use the scheme 'rediss'.\n- `-r <repeat>`: Execute specified command N times.\n- `-i <interval>`: When -r is used, waits `<interval>` seconds per command. It is possible to specify sub-second times like -i 0.1. This interval is also used in --scan and --stat per cycle. and in --bigkeys, --memkeys, --keystats, and --hotkeys per 100 cycles.\n- `-n <db>`: Database number.\n- `--name <name>`: Set the client name.\n- `-2`: Start session in RESP2 protocol mode.\n- `-3`: Start session in RESP3 protocol mode.\n- `-x`: Read last argument from STDIN (see example below).\n- `-X`: Read `<tag>` argument from STDIN (see example below).\n- `-d <delimiter>`: Delimiter between response bulks for raw formatting (default: \\n).\n- `-D <delimiter>`: Delimiter between responses for raw formatting (default: \\n).\n- `-c`: Enable cluster mode (follow -ASK and -MOVED redirections).\n- `-e`: Return exit error code when command execution fails.\n- `-4`: Prefer IPv4 over IPv6 on DNS lookup.\n- `-6`: Prefer IPv6 over IPv4 on DNS lookup.\n- `--raw`: Use raw formatting for replies (default when STDOUT is not a tty).\n- `--no-raw`: Force formatted output even when STDOUT is not a tty.\n- `--quoted-input`: Force input to be handled as quoted strings.\n- `--csv`: Output in CSV format.\n- `--json`: Output in JSON format (default RESP3, use -2 if you want to use with RESP2).\n- `--quoted-json`: Same as --json, but produce ASCII-safe quoted strings, not Unicode.\n- `--show-pushes <yn>`: Whether to print RESP3 PUSH messages.  Enabled by default when STDOUT is a tty but can be overridden with --show-pushes no.\n- `--stat`: Print rolling stats about server: mem, clients, ...\n- `--latency`: Enter a special mode continuously sampling latency. Stats (min/max/avg) are reported in milliseconds with sub-millisecond precision. If you use this mode in an interactive session it runs forever displaying real-time stats. Otherwise if --raw or --csv is specified, or if you redirect the output to a non TTY, it samples the latency for 1 second (you can use -i to change the interval), then produces a single output and exits.\n- `--latency-history`: Like --latency but tracking latency changes over time. Default time interval is 15 sec. Change it using -i.\n- `--latency-percentiles <p1,p2,...>`: Also report the given latency percentiles in milliseconds (e.g. 50,99,99.9) in --latency and --latency-history modes. Resolution is limited by the sample count: a percentile finer than 100/samples resolves to the maximum, so use a longer interval (-i) for meaningful high percentiles.\n- `--latency-dist`: Shows latency as a spectrum, requires xterm 256 colors. Default time interval is 1 sec. Change it using -i.\n- `--vset-recall <key>`: Enable VSIM recall test mode for the specified key (that must be a vector set). Random vectors are created mixing components from other elements. A VSIM is then executed and checked against ground truth.\n- `--vset-recall-count <count>`: How many top elements to fetch per query.\n- `--vset-recall-ef <ef>`: HSNW EF (search effort) to use. Default 500.\n- `--vset-recall-ele <count>`: Number of elements used to compose query vectors Default 1.\n- `--lru-test <keys>`: Simulate a cache workload with an 80-20 distribution.\n- `--replica`: Simulate a replica showing commands received from the master.\n- `--rdb <filename>`: Transfer an RDB dump from remote server to local file. Use filename of \"-\" to write to stdout.\n- `--functions-rdb <filename>`: Like --rdb but only get the functions (not the keys) when getting the RDB dump file.\n- `--pipe`: Transfer raw Redis protocol from stdin to server.\n- `--pipe-timeout <n>`: In --pipe mode, abort with error if after sending all data. no reply is received within `<n>` seconds. Default timeout: 30. Use 0 to wait forever.\n- `--bigkeys`: Sample Redis keys looking for keys with many elements (complexity).\n- `--memkeys`: Sample Redis keys looking for keys consuming a lot of memory.\n- `--memkeys-samples <n>`: Sample Redis keys looking for keys consuming a lot of memory. And define number of key elements to sample\n- `--keystats`: Sample Redis keys looking for keys memory size and length (combine bigkeys and memkeys).\n- `--keystats-samples <n>`: Sample Redis keys looking for keys memory size and length. And define number of key elements to sample (only for memory usage).\n- `--cursor <n>`: Start the scan at the cursor `<n>` (usually after a Ctrl-C). Optionally used with --keystats and --keystats-samples.\n- `--top <n>`: To display `<n>` top key sizes (default: 10). Optionally used with --keystats and --keystats-samples.\n- `--hotkeys`: Sample Redis keys looking for hot keys. only works when maxmemory-policy is *lfu.\n- `--scan`: List all keys using the SCAN command.\n- `--pattern <pat>`: Keys pattern when using the --scan, --bigkeys, --memkeys, --keystats or --hotkeys options (default: *).\n- `--count <count>`: Count option when using the --scan, --bigkeys, --memkeys, --keystats or --hotkeys (default: 10).\n- `--quoted-pattern <pat>`: Same as --pattern, but the specified string can be quoted, in order to pass an otherwise non binary-safe string.\n- `--intrinsic-latency <sec>`: Run a test to measure intrinsic system latency. The test will run for the specified amount of seconds.\n- `--eval <file>`: Send an EVAL command using the Lua script at `<file>`.\n- `--ldb`: Used with --eval enable the Redis Lua debugger.\n- `--ldb-sync-mode`: Like --ldb but uses the synchronous Lua debugger, in this mode the server is blocked and script changes are not rolled back from the server memory.\n- `--cluster <command> [args...] [opts...]`: Cluster Manager command and arguments (see below).\n- `--verbose`: Verbose mode.\n- `--no-auth-warning`: Don't show warning message when using password on command line interface.\n- `--help`: Output this help and exit.\n- `--version`: Output version and exit.\n\n#### Cluster Manager Commands\n\nUse --cluster help to list all available cluster manager commands.\n\n\n#### Examples\n\n- `redis-cli -u redis://default:PASSWORD@localhost:6379/0`\n- `cat /etc/passwd | redis-cli -x set mypasswd`\n- `redis-cli -D \"\" --raw dump key > key.dump && redis-cli -X dump_tag restore key2 0 dump_tag replace < key.dump`\n- `redis-cli -r 100 lpush mylist x`\n- `redis-cli -r 100 -i 1 info | grep used_memory_human:`\n- `redis-cli --quoted-input set '\"null-\\x00-separated\"' value`\n- `redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3`\n- `redis-cli --scan --pattern '*:12345*'`\n- `redis-cli --scan --pattern '*:12345*' --count 100`\n(Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n\nWhen no command is given, redis-cli starts in interactive mode. Type \"help\" in interactive mode for information on available commands and settings."
    }
  ],
  "examples": [
    {
      "id": "string-quoting-and-escaping-ex0",
      "language": "plaintext",
      "code": "127.0.0.1:6379> SET mykey \"Hello\\nWorld\"\nOK\n127.0.0.1:6379> GET mykey\nHello\nWorld",
      "section_id": "string-quoting-and-escaping"
    },
    {
      "id": "string-quoting-and-escaping-ex1",
      "language": "plaintext",
      "code": "127.0.0.1:6379> AUTH some_admin_user \">^8T>6Na{u|jp>+v\\\"55\\@_;OU(OR]7mbAYGqsfyu48(j'%hQH7;v*f1H${*gD(Se'\"",
      "section_id": "string-quoting-and-escaping"
    },
    {
      "id": "usage-ex0",
      "language": "text",
      "code": "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]",
      "section_id": "usage"
    }
  ]
}
