In Redis, databases are typically distinguished by simple integer indices starting from 0. Redis's default configuration file provides 16 logical databases with indices ranging from 0 to 15. You can adjust this number by setting the databases directive in the Redis configuration file redis.conf.
To list all Redis databases, you cannot directly retrieve a list of databases with a single command because Redis does not provide such a command. However, you can determine if a database exists by attempting to select it, which can be done using the SELECT command that allows switching to a specified database index.
For example, you can write a script or attempt to select databases one by one from 0 until the command returns an error, typically because the database index exceeds the configured range. Here is a simple shell command example using redis-cli to attempt listing all available databases:
shellfor db_index in {0..15}; do echo "SELECT $db_index" redis-cli -n $db_index PING done
The above script attempts to select databases from 0 to 15 and sends a PING command to each. If the PING command returns PONG, it can be considered that the database exists. If an error is returned, it indicates that the database does not exist or the index exceeds the configured range, and the loop stops.
It is worth noting that the multi-database feature in Redis is not recommended in the community, especially in high-complexity scenarios. Therefore, in practice, it is usually unnecessary to list all databases. A more common practice is to use a single Redis instance for a single database; for logical data isolation, multiple Redis instances or other mechanisms like prefixes can be used.