【问题标题】:Perform if selection statement on a variable which can cycle through values?对可以循环遍历值的变量执行 if 选择语句?
【发布时间】:2020-06-07 06:42:17
【问题描述】:

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

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

我想要一些方法来扩大对程序的监控范围,即在脚本运行时关闭更多程序。例如,如果 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}"```

【问题讨论】:

  • 把你的终止代码放在一个函数中。然后program="firefox nautilus"; for p in $program; do my_kill_function $p; done

标签: linux bash ubuntu if-statement unix


【解决方案1】:

只需使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-24
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    相关资源
    最近更新 更多