Shell脚本帮助 - 接受输入并在BackGround中运行?

roa*_*cha 5 shell scripting ksh

我有一个shell脚本,在第一行中我要求用户输入他们希望脚本运行的分钟数:

 #!/usr/bin/ksh
echo "How long do you want the script to run for in minutes?:\c"
read scriptduration
loopcnt=0
interval=1
date2=$(date +%H:%M%S)
(( intervalsec = $interval * 1 ))
totalmin=${1:-$scriptduration}
(( loopmax = ${totalmin} * 60 ))

ofile=/home2/s499929/test.log
echo "$date2 total runtime is $totalmin minutes at 2 sec intervals"
while(( $loopmax > $loopcnt ))
do
  date1=$(date +%H:%M:%S)
   pid=`/usr/local/bin/lsof | grep 16752 | grep LISTEN |awk '{print $2}'` > /dev/null 2>&1
   count=$(netstat -an|grep 16752|grep ESTABLISHED|wc -l| sed "s/ //g")
   process=$(ps -ef | grep $pid | wc -l | sed "s/ //g")
   port=$(netstat -an | grep 16752 | grep LISTEN | wc -l| sed "s/ //g")
  echo "$date1 activeTCPcount:$count activePID:$pid activePIDcount=$process listen=$port" >> ${ofile}
  sleep $intervalsec
  (( loopcnt = loopcnt + 1 ))
done
Run Code Online (Sandbox Code Playgroud)

如果我手动输入数值,它的效果很好.但如果我想运行3个小时,我需要启动脚本以在后台运行.

我试过运行./scriptname&,我得到了这个:

$ How long do you want the test to run for in minutes:360
ksh: 360:  not found.
[2] + Stopped (SIGTTIN)        ./test.sh &
Run Code Online (Sandbox Code Playgroud)

脚本死了.这是可能的,关于我如何接受这一个输入然后在后台运行的任何建议?谢谢!!!

Usa*_*agi 3

你可以这样做:

test.sh arg1 arg2 &
Run Code Online (Sandbox Code Playgroud)

只需在 bash 脚本中将arg1arg2分别称为$1$2即可。($0 是脚本的名称)

所以,

test.sh 360 &
Run Code Online (Sandbox Code Playgroud)

会将 360 作为第一个参数传递给 bash 或 ksh 脚本,在脚本中可以将其称为$1 。

所以你的脚本的前几行现在是:

#!/usr/bin/ksh
scriptduration=$1
loopcnt=0
...
...
Run Code Online (Sandbox Code Playgroud)