![使用 bash 脚本安装 Redis,设置配置文件](https://linux22.com/image/903038/%E4%BD%BF%E7%94%A8%20bash%20%E8%84%9A%E6%9C%AC%E5%AE%89%E8%A3%85%20Redis%EF%BC%8C%E8%AE%BE%E7%BD%AE%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6.png)
我想创建一个 bash 脚本,自动安装 redis:
我的问题是更改两个文件中的行:
#Install Redis
sudo apt install redis-server
sudo nano /etc/redis/redis.conf
我需要找到一行并进行更改。监督指令默认设置为否。
# Note: these supervision methods only signal "process is ready."
# They do not enable continuous liveness pings back to your supervisor.
supervised systemd # this line to change
sudo systemctl reload redis.service
sudo nano /etc/redis/redis.conf
需要取消注释(如果存在,请删除#):
bind 127.0.0.1 ::1
也可以测试一下吗?
redis-cli
在随后的提示中,使用 ping 命令测试连通性:
平
Output
PONG
或检查状态?
sudo systemctl status redis
答案1
是的,这是可能的,但你做得不够好。这是一个批处理过程,所以不要使用nano
,而是使用文本处理工具。不要在每个命令前面加上前缀sudo
,而是将整个命令包装在脚本中,然后使用sudo
来执行脚本。
类似于(“类似于”的意思是“我没有尝试过这个,也没有安装 redis-server。我把这个视为我已经多次完成的任务的另一个例子,但它应该可以工作”):
#!/bin/bash
if [[ $(id -u) != 0 ]] ; then
echo "Must be run as root" >&2
exit 1
fi
apt update
apt install redis-server
# Just in case, ...
systemctl stop redis-server
# Change "supervised no" so "supervised systemd"? Question is unclear
# If "#bind 127.0.0.1 ::1", change to "bind 127.0.0.1 ::1"
sed -e '/^supervised no/supervised systemd/' \
-e 's/^# *bind 127\.0\.0\.1 ::1/bind 127.0.0.1 ::1' \
/etc/redis/redis.conf >/etc/redis/redis.conf.new
# $(date +%y%b%d-%H%M%S) == "18Aug13-125913"
mv /etc/redis/redis.conf /etc/redis/redis.conf.$(date +%y%b%d-%H%M%S)
mv /etc/redis/redis.conf.new /etc/redis/redis.conf
systemctl start redis-server
# give redis-server a second to wake up
sleep 1
if [[ "$( echo 'ping' | /usr/bin/redis-cli )" == "PONG" ]] ; then
echo "ping worked"
else
echo "ping FAILED"
fi
systemctl status redis
systemctl status redis-server
exit 0