arrays - 命令在终端中有效,但在 Bash 脚本中无效

标签 arrays bash shell

我是使用 cpanel 托管面板部署的几个网络服务器的系统管理员。我正在尝试完成备份脚本。 Cpanel 捆绑了两个命令,将在此脚本中使用。这些命令是;

1. whmapi1 modifyacct user=USERNAME BACKUP=[01]

This Command has booleans to set, what it does is either enable or disable backup for a specific user.

2. /usr/local/cpanel/bin/backup --force

Once backup is enabled for a user/users, then this command starts the backup process on the server.

这是我的脚本逻辑和脚本。

#!/bin/bash

数组

L=($( comm -23 <(du -h --max-depth=1 /home 2>/dev/null | grep G |  awk -F"/" '{print $NF}' | sort | egrep -vw '(home|virtfs)') <(ls -al /var/cpanel/suspended/ | grep -v 'lock' | sort) ))

Above Array contains all the account whose home directories have exceeded 1GB limit.

S=($(comm -23 <(du -h --max-depth=1 /home 2>/dev/null | egrep -v '(!G|.cp|cP|clamav)' | awk -F"/" '{print $NF}' | sort | egrep -vw '(home|virtfs)') <(ls -al /var/cpanel/suspended/ | grep -v 'lock' | sort) ))

Above Array contains all the account whose home directories are less than 1GB limit.

whmapi1 modifyacct user=${L[@]} BACKUP=0 && whmapi1 modifyacct user=${S[@]} BACKUP=0

Above command disables backup for all users for start, to start from scracth.

whmapi1 modifyacct user=${S[@]} BACKUP=1

T

his command enables backup for all accounts whose home dirs are less than 1 GB

/usr/local/cpanel/bin/backup --force

This command starts backup process for all enabled users.

逻辑是,我想首先创建小帐户的备份,然后当完成后,我将为较大的帐户运行它。

问题:直接在终端中运行时,所有命令都会成功执行,但通过脚本运行时则不会。帐户启用和禁用时出现问题。 它要么禁用所有帐户,要么启用所有帐户,而不是部分帐户,正如脚本逻辑所预期的那样。

任何人都可以指出我缺少的地方和内容吗? 预先感谢!

最佳答案

${l[@]} 扩展为 user1 user2 user3 ...,因此 user=${L[@]}展开为 user=user1 user2 user3 ...,如果你想为 foreach user 带来乐趣,你需要循环遍历 users。

du_buff=$(du -h --max-depth=1 /home 2>/dev/null)
lock_buff=$(ls -al /var/cpanel/suspended/ | grep -v 'lock' | sort)
L=($(comm -23 <(echo "$du_buff" | grep G |  awk -F"/" '{print $NF}' | sort | egrep -vw '(home|virtfs)') <(echo "$lock_buff") ))
S=($(comm -23 <(echo "$du_buff" | egrep -v '(!G|.cp|cP|clamav)' | awk -F"/" '{print $NF}' | sort | egrep -vw '(home|virtfs)') <(echo "$lock_buff") ))

# for every user in L and S
for user in "${L[@]}" "${S[@]}"; do
     whmapi1 modifyacct user=$user BACKUP=0
done
# for every user in S
for user in "${S[@]}"; do
     whmapi1 modifyacct user=$user BACKUP=1
done
/usr/local/cpanel/bin/backup --force

关于arrays - 命令在终端中有效,但在 Bash 脚本中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346029/

相关文章:

javascript - 如何通过具有数组行的第一项的值来删除/删除javascript数组中的一行?

shell - 在别名中使用其他命令

android - 在 Android adb shell 中运行 shell 脚本

java - 规范化 IP 地址

shell - 为 awk 编写 shell 包装器脚本

javascript - For循环: TypeError: Cannot read property '0' of undefined

python - 使用 numpy 从过滤、排序的数组返回索引

javascript - 数组操作/映射返回未定义

bash - 从作为另一个用户运行的后台进程获取 PID

bash - 如何为每个标准输入行执行命令?