0
0
RedisHow-ToBeginner · 3 min read

How to Use SCRIPT LOAD in Redis: Syntax and Examples

Use SCRIPT LOAD in Redis to load a Lua script into the server's script cache and get its SHA1 hash. This hash can then be used with EVALSHA to run the script efficiently without sending the full script every time.
📐

Syntax

The SCRIPT LOAD command loads a Lua script into Redis's script cache and returns its SHA1 hash. This hash uniquely identifies the script and can be used to execute it later with EVALSHA.

Syntax:

SCRIPT LOAD <script>

Where:

  • <script> is the Lua script code as a string.
redis
SCRIPT LOAD "return redis.call('PING')"
Output
"e0e1f1d7a6a1b2c3d4e5f67890123456789abcd1"
💻

Example

This example shows how to load a simple Lua script that returns the string 'Hello, Redis!' and then execute it using the returned SHA1 hash.

redis
127.0.0.1:6379> SCRIPT LOAD "return 'Hello, Redis!'"
"3f0a1b2c3d4e5f67890123456789abcdef123456"
127.0.0.1:6379> EVALSHA 3f0a1b2c3d4e5f67890123456789abcdef123456 0
"Hello, Redis!"
Output
"Hello, Redis!"
⚠️

Common Pitfalls

Common mistakes when using SCRIPT LOAD include:

  • Not using the returned SHA1 hash with EVALSHA, causing errors.
  • Modifying the script after loading it without reloading, which leads to mismatched hashes.
  • Trying to run EVALSHA with a SHA1 hash that was never loaded, resulting in a NOSCRIPT error.

Always ensure the script is loaded and the correct SHA1 hash is used for execution.

redis
127.0.0.1:6379> EVALSHA deadbeefdeadbeefdeadbeefdeadbeefdeadbeef 0
(error) NOSCRIPT No matching script. Please use SCRIPT LOAD.
Output
(error) NOSCRIPT No matching script. Please use SCRIPT LOAD.
📊

Quick Reference

CommandDescription
SCRIPT LOAD