How to Use Stash and Unstash in Jenkins Pipeline
In Jenkins pipelines, use
stash to save files temporarily and unstash to retrieve them in another stage. This helps share files between stages without writing to permanent storage.Syntax
The stash command saves files with a name for later use, and unstash retrieves those files by name in another stage.
stash syntax:
stash name: 'stashName', includes: 'filesPattern'
unstash syntax:
unstash 'stashName'
Here, name is the identifier for the stash, and includes specifies which files to save.
groovy
stash name: 'myFiles', includes: '**/*.txt' unstash 'myFiles'
Example
This example shows how to stash a file in one stage and unstash it in a later stage to use it.
groovy
pipeline {
agent any
stages {
stage('Create File') {
steps {
sh 'echo Hello Jenkins > greeting.txt'
stash name: 'greetingFiles', includes: 'greeting.txt'
}
}
stage('Use File') {
steps {
unstash 'greetingFiles'
sh 'cat greeting.txt'
}
}
}
}Output
Hello Jenkins
Common Pitfalls
- Forgetting to
unstashthe files before using them causes errors because the files are not present. - Using the same stash name in multiple places without clearing can overwrite files unexpectedly.
stashonly works within the same pipeline run; it cannot share files across different runs.- Including too many files in
stashcan slow down the pipeline due to large data transfer.
groovy
pipeline {
agent any
stages {
stage('Wrong Usage') {
steps {
// Trying to use file without unstashing
sh 'cat greeting.txt' // This will fail if file is not present
}
}
stage('Correct Usage') {
steps {
unstash 'greetingFiles'
sh 'cat greeting.txt' // This works
}
}
}
}Quick Reference
| Command | Purpose | Example |
|---|---|---|
| stash | Save files temporarily in pipeline | stash name: 'data', includes: '**/*.log' |
| unstash | Retrieve stashed files in another stage | unstash 'data' |
Key Takeaways
Use stash to save files and unstash to retrieve them between pipeline stages.
Always unstash files before accessing them to avoid errors.
Stash names must be unique per pipeline run to prevent overwriting.
Stash and unstash only share files within the same pipeline execution.
Keep stashed files minimal to maintain pipeline speed.