从屏幕读取变量,从单独的文件中读取时间



我想从屏幕上读取变量,而不是在文件中键入。我尝试了以下方法:

#!/bin/bash
STARTED_TIME=10:46:20
RECORDED_TIME=(
11:03:00
11:24:00
11:27:00
11:32:00
)
SEC1=$(date +%s -d "${STARTED_TIME}")
for d in "${RECORDED_TIME[@]}"
do
  SEC2=$(date +%s -d "$d")
  DIFFSEC=$(( SEC2 - SEC1 ))
  echo "$DIFFSEC"
done

前一个工作正常。现在我正在寻找两件事。首先是从屏幕命令读取SATRED_TIME,另一个是从另一个单独的文件中读取RECORDED_TIME。我将不胜感激任何帮助。

     #!/bin/bash  
     echo "What is the started time?"
     read time
  STARTED_TIME=$time 
RECORDED_TIME=(
recorded_time.txt
)
SEC1=$(date +%s -d "${STARTED_TIME}")
for d in "${RECORDED_TIME[@]}"
do
  SEC2=$(date +%s -d "$d")
  DIFFSEC=$(( SEC2 - SEC1 ))
  echo "$DIFFSEC"
done
cat Recorded_time.txt
11:03:00 
11:24:00
11:27:00
11:32:00

你想写这样的东西:

$ cat time.sh
#!/bin/bash
read -p "What is the started time? " started_time
mapfile -t recorded_time < Recorded_time.txt
sec1=$(date +%s -d "${started_time}") || exit 2
for rec_time in "${recorded_time[@]}"; do
    sec2=$(date +%s -d "$rec_time")
    diffsec=$(( sec2 - sec1 ))
    echo "$diffsec"
done

然后,你可以做

$ bash time.sh
What is the started time? 11:00:00
180
1440
1620
1920

我正在使用 read -p 来指定 read 命令的提示,以及将文件行读取到 shell 数组中的 mapfile 命令。

此外,最好避免使用 ALL_CAPS_VARNAMES:这些应该仅由 shell 使用。

最新更新