【问题标题】:Two-words argument in shell script - unixshell脚本中的两个词参数 - unix
【发布时间】:2015-03-12 18:58:18
【问题描述】:

我的 shell 脚本有问题。它应该读取参数:索引、日期、time1(间隔的开始)、time2(间隔的结束)。 它应该计算用户(索引)在时间间隔 time1-time2 内登录给定日期的次数。 例如:121212 "Jan 14" 00 12

这可行,但我对参数日期有疑问。它不承认这是一个论点。它在 1 月和 14 日将其拆分,这是一个大问题。 我已经在互联网上搜索了几个小时,但我无法在任何地方找到解决方案。 这是我的代码:

#!/bin/bash

read user date time1 time2

list=`last | grep ^$user.*$date | awk '{ print $7 }'`

start=$time1
end=$time2

echo "start $start"
echo "end $end"

count=0
for el in $list ;
do
    login=$el
    echo "najava $najava"

    checkIf(){
            current=$login
            [[ ($start = $current || $start < $current) && ($current = $end || $current < $end) ]]
    }

    if checkIf; then
            count=`expr $count + 1`
            ip=`last | grep ^$user.*$date.*$login | awk '{ print $3 }'`
            echo $ip >> address.txt
    else
            continue
    fi
  done

 echo "The user has logged in $count times in the given time interval"

【问题讨论】:

  • 您的脚本似乎没有接受任何参数,那么您在说哪些“参数”?

标签: bash shell unix arguments


【解决方案1】:

来自read 的 man 条目,

The characters in IFS are used to split the line into words.

而您系统上的默认IFS 可能就是该空间。您可以通过转义您不想用作单词分隔符的任何空格来立即解决您的问题:

121212 Jan\ 14 00 12

应该为您的目的工作。

但是,当然,这不是一个理想的解决方案。一种可能性是在命令行上将参数传递给脚本,而不是在调用脚本后通过读取,例如

#!/bin/bash

user="$1"
date="$2"
time1="$3"
time2="$4"
#etc

有关处理命令行参数的更多详细信息,请参阅http://www.shelldorado.com/goodcoding/cmdargs.html

【讨论】:

    猜你喜欢
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多