iT邦幫忙

0

Ubuntu執行sh檔讀取txt內容,並背景自動執行

我有一個test.sh檔,如下:

#!/bin/bash
IDnumber=../R123456789
cd $IDnumber
gitbook pdf
if [ $? -eq 0 ];then echo success; else echo fail; fi
exit

其中gitbook pdf指令是將R123456789底下的資料內容轉成PDF檔
下一行是執行完後回傳成功與否的訊息

另外我有一個test.txt會存放員工ID號碼,內容如下:

R123456789,
A123456789,
H227654321,
...
...
...

我的資料結構如下:

TEST
 |
 ├─script
 |  ├─test.txt
 |  └─test.sh
 ├─R123456789
 |  ├─SUMMARY.md
 |  └─README.md
 ├─A123456789
 |  ├─SUMMARY.md
 |  └─README.md
 ├─H227654321
 |  ├─SUMMARY.md
 |  └─README.md
 |
 ...
 ...
 ...

我想要test.sh檔去撈test.txt裡面的內容存入陣列
並用for迴圈去執行cd指令與gitbook指令
因為每個ID資料夾都要執行一次cd指令與gitbook指令

問題一:如何讓test.sh去撈test.txt裡面的ID資料?
問題二:我像讓test.sh每隔1小時自動執行,有方法做到嗎?

froce iT邦大師 1 級 ‧ 2017-04-27 12:09:54 檢舉
1.可參考:
http://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable

2.cron
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
bizpro
iT邦大師 1 級 ‧ 2017-04-27 14:37:03
最佳解答

把這腳本設定crontab執行即可, 請修改test.txt或使用參數:

#!/bin/bash
SDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LIST=$SDIR/test.txt
if test  -z $LIST -o ! -f $LIST; then exit 1; fi
BDIR=$(dirname $SDIR)
while IFS= read ID; do
  ID=$(echo $ID | tr -d ',')
  if test ! -z "$ID" -a -d $BDIR/$ID; then
    cd $BDIR/$ID
    gitbook pdf 1>/dev/null 2>&1
  fi
done < "$LIST"

說明

  1. 此腳本可用於crontab中執行,
  2. 有盡量檢查test.txt中的內容, 與相關目錄是否存在.
  3. 如果使用不同於test.txt的清單, 請自行修改LIST=...,
  4. 我沒有用過已沒有更新的gitbook, 不能預期它會產生什麼錯誤, 還有產出的pdf的問題, 另外, gitbook使用可能會停止的phantomjs.

20170427T1933
修正:
原先判斷LIST的程式由

[[ -z $LIST ]] && exit 1;

改為:

if test -z $LIST -o ! -f $LIST; then exit 1; fi

對不起~~/images/emoticon/emoticon16.gif
您寫的很仔細~我看得沒有很懂~= =

大概是因為不是很懂bash的程式碼~

另外~我有去查怎麼執行crontab
要下crontab -e,我執行後出現如下資訊:

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

第1~您教的那段bash程式直接加在上面的資訊之後嗎?
第2~既然sh檔不需要了,那txt檔是要放在哪個位置上呢?因為不懂程式碼是怎麼去找到我的txt檔..(慚愧)

bizpro iT邦大師 1 級 ‧ 2017-04-28 09:40:37 檢舉
  1. 我寫的是test.sh的全部內容,
  2. 記得chmod +x test.sh
  3. 相對路徑是依您的描述,test.txt也是和test.sh在一起的
  4. crontab的內容, 在每小時整點時會執行
0 * * * * <命令的全路徑>/test.sh

如果您對bash不熟, 建議您找資料學.

了解~謝謝您~^^

我要發表回答

立即登入回答