You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写基于菜单的LUKS加密Bash脚本,解决cryptsetup报错问题

问题原因

你脚本中的变量赋值逻辑存在语法错误,所有加密配置类变量(cipher、key、hash、pbkdf)都未被正确赋值,空值传入cryptsetup命令后触发数值无效报错。
你混淆了Bash中条件判断和变量赋值的语法:[[ 变量 == 值 ]]是判断两个值是否相等的条件表达式,不会执行赋值操作,脚本运行完所有选择逻辑后,上述变量全部是空值,导致cryptsetup的-s(密钥长度)等需要数值的参数没有拿到合法输入。

修复方案

将所有条件分支内的条件判断语句替换为标准变量赋值语句,格式为变量名="值",不需要包裹双括号。
另外建议新增非法输入退出逻辑,避免用户选错选项后脚本依然携带空参数执行加密操作。

修正后的完整代码
#!/usr/bin/env bash

## Ask user for device.
echo "Device:" 
read -r device

## Ask user for cipher.
echo "Available ciphers:" 
echo "AES     [0]" 
echo "Serpent [1]" 
echo "Twofish [2]" 
echo "Cipher:" 
read -r cipherin
if [[ $cipherin == "0" ]]; then
        cipher="aes-xts-plain64"
elif [[ $cipherin == "1" ]]; then
        cipher="serpent-xts-plain64"
elif [[ $cipherin == "2" ]]; then
        cipher="twofish-xts-plain64"
else 
        echo "Invalid choice."
        exit 1
fi

## Ask user for key length.
echo "Available key lengths (bits):" 
echo "128 [0]" 
echo "256 [1]" 
echo "Key length:" 
read -r keyin
if [[ $keyin == "0" ]]; then
        key="256"
elif [[ $keyin == "1" ]]; then
        key="512"
else 
        echo "Invalid choice."
        exit 1
fi

## Ask user for hash.
echo "Available hashes:" 
echo "SHA-1     [0]" 
echo "SHA-256   [1]" 
echo "SHA-512   [2]" 
echo "Whirlpool [3]:" 
echo "Hash:" 
read -r hashin
if [[ $hashin == "0" ]]; then
        hash="sha1"
elif [[ $hashin == "1" ]]; then
        hash="sha256"
elif [[ $hashin == "2" ]]; then
        hash="sha512"
elif [[ $hashin == "3" ]]; then
        hash="whirlpool"
else 
        echo "Invalid choice."
        exit 1
fi

## Ask user for PBKDF.
echo "Available PBKDFs:" 
echo "argon2i  [0]" 
echo "argon2id [1]" 
echo "pbkdf2   [2]"
read -r pbkdfin
if [[ $pbkdfin == "0" ]]; then
        pbkdf="argon2i"
elif [[ $pbkdfin == "1" ]]; then
        pbkdf="argon2id"
elif [[ $pbkdfin == "2" ]]; then
        pbkdf="pbkdf2"
else 
        echo "Invalid choice."
        exit 1
fi

## Ask user for iteration time.
echo "Iteration time (ms):" 
read -r iteration

## Encrypt drive using LUKS.
echo "Encrypting..." 
sudo cryptsetup --type luks2 -c "${cipher}" -h "${hash}" \
 -i "${iteration}" -s "${key}" --pbkdf "${pbkdf}" --use-urandom \
 -y luksFormat "${device}"
补充说明

修改时同时给所有变量加上了双引号避免路径/参数含空格时出错,read加了-r参数避免转义符异常,所有非法输入分支新增exit 1直接终止脚本,防止无效参数被传入加密命令。

内容的提问来源于stack exchange,提问作者user16448786

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:09:00