编辑:好的,我已经确信数组不是一个好主意!
#!/bin/bash
# /bin/sh cannot be used with this script as "=~" is bash only
[snip]
sqlite $database "create table ports (port TEXT PRIMARY KEY, name TEXT, comment TEXT);" # name = short name, i.e. "https"
[snip]
getports=$(sqlite $database "SELECT * FROM $ports ORDER BY port ASC";)
if [[ -z ${getports[@]} ]]; then
fail "No ports mapped, set up traefik first!"
fi
APPRISE_API_PORT=$(whiptail --inputbox --title "API Port" "Set the port to call the Apprise API on \nCurrently used ports: \n${getports[@]}" 20 60 "8000" 3>&1 1>&2 2>&3) # Default of port 8000
exitstatus=$?
if [ $exitstatus = "0" ]; then
if [ -z "$APPRISE_API_PORT" ]; then
fail "Entry was blank - please set the port. You cannot leave this blank!"
else
if [[ "${array[*]}" =~ "$APPRISE_API_PORT" ]]; then
fail "Port already in use - please select an unused port"
sqlite variables.db "insert into settings (name,value,comment) values ('$APPRISE_API_PORT', 'apprise', 'The Apprise API port');"
fi
else
echo "User cancelled"
fi
[snip]
注意:bash 变量已被映射,fail 是一个函数,并且用于替换 docker-compose.yml 文件中的值的代码等都在剪辑部分中。
项目可以在这里查看https://github.com/animeai/docker-compose/tree/0.1-testing
原始问题:
这里有 Bash 新手-请温柔一点!
这是必要的,因为 sqlite 存在缺陷,不允许存储数组(据我所知 - 如果我错了请纠正我!)。数据库表有 3 列,“名称”(即“https”)、“值”和“注释” - 全部都是文本字符串。
#!/bin/bash
ports=$(sqlite database.db "SELECT value FROM settings WHERE name = 'USED_PORTS'";) # Returns "80,443,8000,8080,9999"
[convert $ports to array] # Need help with this!
ports+=("1234") # Append port "1234" to array
[sort array low to high] # Need help with this!
[convert $ports array to string] # Need help with this - string should now read "80,443,1234,8000,8080,9999"
sqlite database.db "UPDATE settings set value = '$ports' where name = 'USED_PORTS'; # Insert back into the database
是不是只需在数据库中创建一个新表,命名为 portsused(名称、端口、注释),然后从表中使用“SELECT port from portsused”并按值升序排序,这样会更简单?不过,我更喜欢单个数据库条目,以简化未来的编码,因为运行足够多的应用程序时,端口数量可能会变得非常大。在使这个基本功能正常工作后,我会在添加新端口时搜索数组,以确保没有冲突。
答案1
我并不鼓励你这样做,显然针对数据库的建议在这里至关重要。
但是,有一个 shell 方法可以实现您的目标,即在 csv 字符串中插入 1234 到它的位置:
row="80,443,8000,8080,9999"
new=$(echo "1234,$row" | tr , '\n' | sort -n | paste -sd,)
declare -p row new
输出
declare -- row="80,443,8000,8080,9999"
declare -- new="80,443,1234,8000,8080,9999"