gpt4 book ai didi

linux - 对可以循环遍历值的变量执行 if 选择语句?

转载 作者:行者123 更新时间:2023-12-04 18:59:58 24 4
gpt4 key购买 nike

我写了以下脚本来帮助我学习。

如果在执行脚本时发现正在运行,该程序会关闭分散注意力的应用程序。

我想要一些方法来扩大对程序的监控范围,即在脚本运行时关闭更多程序。例如,如果 nautilus、neverball、transmission 等也在运行,它们应该遭遇相同的命运,即 pkill。

我不想写更多行,即多写if..then陈述。我想要某种方式让相同的代码在每次迭代时循环遍历所有这些值的变量 $program。像数组一样的东西?我不完全确定 bash 的做法,所以如果你能想到更好的方法,请告诉我。

#!/bin/bash

bold=$(tput bold)
normal=$(tput sgr0)
echo "Slotmachine has begun. Do not kill this terminal or you\'ll mess up directory permissions."
echo ...
echo "Type the ending time for slot ${bold}( CAUTION! Time format must be: 05:03 or 11:34 ):- ${normal}"
read endtime

cd /home/user1

for folder in *;
do
if [[ "$folder" != "Documents" ]] #documents has my physics notes.
then
chmod u-r $folder
echo Permissions taken for $folder.
fi
done


sleep 3;



declare -i counter=1 , killtimer=5;

program="firefox"

until [[ $( date +%H:%M ) == $endtime ]]
do
date

echo "Study slot till $endtime"
echo "..."
echo "${bold}Focus".
counter=$((counter+1))
sleep 1
clear
if pgrep -x $program > /dev/null
then
for killtimer in {5..1}
do
echo "${bold}Browsing isn't allowed. If you need to browse, wait till the end. Do not kill this terminal or you'll mess up permissions."
echo "${bold} $program will be killed in.. $killtimer seconds."
sleep 1
clear
killtimer=$((killtimer-1))
done
pkill $program
fi

done

for folder in *;
do
if [[ "$folder" != "Documents" ]]
then
chmod u+r $folder
echo "${normal}Permissions given for $folder".
fi
done

sleep 2
echo ...
echo "${bold} Slotmachine session has ended. ${normal}"```

最佳答案

只需使用 bash 数组:

programs=(firefox nautilus)

然后迭代它:
for program in "${programs[@]}"; do
if pgrep -x "$program" > /dev/null; then
for killtimer in {5..1}; do
echo "${bold}Browsing isn't allowed. If you need to browse, wait till the end. Do not kill this terminal or you'll mess up permissions."
echo "${bold} $program will be killed in.. $killtimer seconds."
sleep 1
clear
# killtimer=$((killtimer-1)) # remove this..., it's a `for i in <this>`
done
pkill $program
fi
done

关于linux - 对可以循环遍历值的变量执行 if 选择语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62241815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com