Here's a small zsh function that can convert between IPFS CID v0 and v1:
```zsh
# Convert between IPFS CID v0 and v1
cid_convert() {
local cid="$1"
if [[ -z "$cid" ]]; then
echo "Usage: cid_convert <CID>"
echo "Converts between IPFS CID v0 and v1 formats"
return 1
fi
# Check if ipfs command is available
if ! command -v ipfs &> /dev/null; then
echo "Error: ipfs command not found. Please install IPFS."
return 1
fi
# Detect CID version and convert
if [[ "$cid" =~ ^Qm[1-9A-HJ-NP-Za-km-z]{44}$ ]]; then
# CID v0 format (starts with Qm, 46 chars total)
echo "Converting CID v0 to v1..."
ipfs cid format -v 1 -b base32 "$cid" 2>/dev/null || {
echo "Error: Invalid CID v0 or conversion failed"
return 1
}
elif [[ "$cid" =~ ^b[a-z2-7]{58}$ ]] || [[ "$cid" =~ ^[a-z2-7]+$ && ${#cid} -gt 46 ]]; then
# CID v1 format (base32 encoded, starts with 'b' or longer base32 string)
echo "Converting CID v1 to v0..."
ipfs cid format -v 0 "$cid" 2>/dev/null || {
echo "Error: Invalid CID v1 or conversion failed (note: not all v1 CIDs can be converted to v0)"
return 1
}
else
echo "Error: Unrecognized CID format"
echo "Expected:"
echo " - CID v0: Qm... (46 characters, base58)"
echo " - CID v1: b... (base32) or other multibase formats"
return 1
fi
}
```
You can also create a more compact version if you prefer:
```zsh
# Compact version
cid_convert() {
[[ -z "$1" ]] && { echo "Usage: cid_convert <CID>"; return 1; }
command -v ipfs >/dev/null || { echo "Error: ipfs not found"; return 1; }
if [[ "$1" =~ ^Qm[1-9A-HJ-NP-Za-km-z]{44}$ ]]; then
ipfs cid format -v 1 -b base32 "$1"
else
ipfs cid format -v 0 "$1" 2>/dev/null || echo "Error: Conversion failed"
fi
}
```
**Usage:**
Add the function to your `~/.zshrc` file, then:
```bash
# Convert v0 to v1
cid_convert QmYourCIDv0Here
# Convert v1 to v0
cid_convert bafybeiyourCIDv1here
```
**Features:**
- Automatically detects CID version based on format
- Uses IPFS built-in conversion tools for reliability
- Includes error handling for invalid CIDs
- Provides helpful usage information
**Requirements:**
- IPFS must be installed and available in PATH
- Note that not all CID v1s can be converted to v0 (only SHA-256 hashed content)