如何写一个shell脚本来源码编译安装ProFTPD?

How to write a shell script to compile and install ProFTPD by source compilation?

我通过源代码编译安装了 ProFTPD 并成功运行,但我在想,与其单独执行所有步骤,不如使用 bash 脚本完成整个安装,但是我在 shell 脚本方面的知识较少。请帮忙。 这些是我为构建和配置 ProFTPD 而执行的以下命令:

  1. tar -xzf proftpd-1.3.3e.tar.gz

  2. cd proftpd-1.3.3e

  3. ./configure –sysconfdir=/etc

  4. make

  5. make install

  6. ln -s /usr/local/sbin/proftpd /usr/sbin/proftpd

  7. groupadd ftpgroup

  8. useradd -G ftpgroup onedomain -s /sbin/nologin -d /home/onedomain/public_html/

  9. vim /etc/proftpd.conf

    这里我给了用户名,组名,服务器名

  10. vim /etc/init.d/proftpd

    #!/bin/sh
    
    case  in
    'start' )
    /usr/local/sbin/proftpd
    ;;
    
    'stop' )
    kill `ps -ef | grep proftpd | grep -v grep | awk '{print }'` > /dev/null 2>&1
    ;;
    
    *)
    echo "usage: [=11=] {start|stop}"
    
    esac
    
  11. 使用/etc/init.d/proftpd start启动服务。

您输入了哪些命令来编译代码?这些是您在 shell 脚本的第一个版本中需要的命令。

后续版本将允许您更改包含源的存档名称(软件的新版本)、源被提取到的目录(同上)、安装目录等。但第一步是获取您在 shell 脚本中输入的内容。


我没有查看 ProFTP 配置文件的语法,因此您需要正确重写该位。使用 'here documents' 创建配置文件和控制文件(记得在之后正确设置文件的权限)。

tar -xzf proftpd-1.3.3e.tar.gz || exit
cd proftpd-1.3.3e || exit
./configure –sysconfdir=/etc || exit
make || exit
make install || exit

rm -f /usr/sbin/proftpd
ln -s /usr/local/sbin/proftpd /usr/sbin/proftpd

# Check whether these exist before adding them?
groupadd ftpgroup
useradd -G ftpgroup onedomain -s /sbin/nologin -d /home/onedomain/public_html/

# Maybe save old version before overwriting with new?
cat >/etc/proftpd.conf <<'EOF'
username=onedomain
groupname=ftpgroup
servername=localserver
EOF
chmod 644 /etc/proftpd.conf

# Maybe save old version before overwriting with new?
# Maybe add 'restart' option to stop and start?
cat >/etc/init.d/proftpd <<'EOF'
#!/bin/sh

case  in
'start')
    /usr/local/sbin/proftpd
    ;;
'stop')
    kill $(ps -ef | grep proftpd | grep -v grep | awk '{print }') > /dev/null 2>&1
    ;;
*)
    echo "usage: [=10=] {start|stop}" >&2
    ;;
esac
EOF
chmod 755 /etc/init.d/proftpd
/etc/init.d/proftpd start   # restart

从这里开始,每次重复一个名字,就应该把它做成一个变量,然后在脚本的其余部分使用这个变量。

INIT_SCRIPT=/etc/init.d/proftpd
CONF_FILE=/etc/proftpd.conf
BASE_VERSION=proftpd-1.3.3e

tar -xf "${BASE_VERSION}.tar.gz" || exit

在变量名周围使用双引号,这样即使文件路径名中有空格也能正常工作。

请注意,最有可能失败的部分(提取代码和构建软件的部分)受到 || exit 的保护,因此如果出现问题,脚本会退出而不会损坏设置。

我倾向于将提取和构建阶段与安装和配置阶段分开,所以我可以 运行 第一部分作为我,只有 运行 安装和配置作为 root.在我的书中,作为 root 进行开发是危险的(或者,如果您愿意,我认为 root 不应该 运行 编译器)。这是一种过度简化,但适度明智。你可以像 root 一样造成巨大的伤害;尽量减少这样做的机会。构建可靠的第三方软件不同于 root 进行开发 — 而且更可以原谅。但是你应该尽可能少地使用 root(超级用户)权限。