2016年2月29日 星期一

[Linux 常見問題] How do I get the path of a process in Unix / Linux

Source From Here
In Windows environment there is an API to obtain the path which is running a process. Is there something similar in Unix / Linux? Or is there some other way to do that in these environments?

If you want the path of the current executable, look at /proc/$PID/exe, which is a symlink to it. For example:
# ./a.out & // Sleep 10 second
[1] 22383
# ls -hl /proc/22383/exe
lrwxrwxrwx. 1 root root 0 3月 1 11:07 /proc/22383/exe -> /root/PhishTankWH/a.out

2016年2月28日 星期日

[ 英語發燒句 ] Part-19

101. "我同意" 
A. Wow! That was a really scary movie.
B. I'll say. I had to close my eyes whenever the monster appeared.

Note. 類似說法 You can say that again ; You said it; Absolutely, I strongly agree; That's so true. 

102. "亡羊補牢猶未晚" 
A. I turned in my term paper a few days after it was due.
B. Better late than never. Hopefully, your grade won't suffer too much.

103. "拿出錦囊妙計" 
A. How in the world is Tom going to finish the project by tomorrow?
B. I have no idea, but he usually manages to pull a rabbit out of his hat at the last minute.

Note. 由於在魔術表演中常有 "將兔子從帽子裡變出來" 的橋段, 因此這裡引申為神奇的解決問題, 或某人做出驚人之舉. 

104. "我無所謂" 
A. The taxi drivers in the city are raising their prices again.
B. It's no skin off my nose. I always take the subway.

Note. 類似說法 It doesn't matter to me; Not my problem; Makes no difference to me. 

105. "準備妥當; 做好萬全準備" 
A. Are you going to start your science project this weekend?
B. No. I have to get my ducks in a row for my other classes first.

Note. "ducks in a row" 這句話表示 "把事情安排得井然有序". 

106. "不要拖拖拉拉" 
A. I haven't come up with a topic for my term project yet, and it is due in two weeks.
B. Well, don't let the grass grow under your feet; start thinking about it now.

2016年2月25日 星期四

[Linux 常見問題] Shell - WAIT for “any process” to finish

Source From Here
Is there any built-in feature in bash to wait for any process to finish? The wait command only allows one to wait for child processes to finish. I would like to know if there is any way to wait for any process to finish before proceeding in any script. A mechanical way to do this is as follows but I would like to know if there is any built in feature in bash:
- waitProc.sh
  1. #!/bin/sh  
  2. while ps -p $1 > /dev/nulldo  
  3.     echo -e "Wait PID=$1..."  
  4.     sleep 1;  
  5. done  
  6. echo -e "Exit Shell"  
Usage example:
# groovy wait.groovy & // This script will sleep 20 seconds in background
[1] 28572 // The PID of running groovy script
Wait 20 sec...
# ./waitProc.sh 28572 // This script will wait for PID=28572
Wait PID=28572...
Exit Shell
[1]+ Done groovy wait.groovy

There's no builtin. Use kill -0 in a loop for a workable solution:
- waitProc2.sh
  1. #!/bin/sh  
  2. waitPID(){  
  3.     while kill -0 "$1" >> /dev/null 2>&1do  
  4.         sleep 0.5  
  5.     done  
  6. }  
  8. echo -e "Wait PID=$1..."  
  9. $(waitPID $1)  
  10. echo -e "Exit Shell..."  
As noted by several commentators, if you want to wait for processes that you do not have the privilege to send signals to, you have found some other way to detect if the process is running to replace the kill -0 $pidcall. On Linux, test -d "/proc/$pid" works, on other systems you might have to use pgrep (if available) or something like ps | grep ^$pid.

Usage example:
# groovy wait.groovy &
[1] 29042

# ./waitProc2.sh 29042
Wait PID=29042...
Exit Shell...
[1]+ Done groovy wait.groovy

2016年2月22日 星期一

[ 英語發燒句 ] Part-17

94. "我完全搞不懂" 
A. Do you understand the instructions for putting the toy together?
B. No. It's all Greek to me.

Note. Greek 是指 "希臘語", 希臘文向來被視為最艱澀的語言之一, 故被引申為 "難懂, 費解之事". 

95. "直接切入重點吧!" 
A. I think that with the compromise we've both made, we can finally make a deal.
B. Great! Let's get down to brass tacks and finalize this thing.

Note. brass tack 原指 "黃銅釘子", 有一說法是十九世紀時, 黃銅釘用來固定家具的邊框. 家具出問題時, 通常檢查黃銅釘就能找出問題, 故 brass tack 引申 "根本問題; 要點". 

96. "那是一廂情願的想法" 
A. I'm going to buy a fancy sports car. When Karen sees it, she'll think it's cool and agree to date me.
B. That's wishful thinking. She's not attracted to you because of your lousy personality, not because of your piece-of-junk car.

Note. 類似說法 That's just a pipe dream (那只是癡人說夢

97. "一副自以為是的樣子" 
A. What's with Tom acting all high and mighty?
B. He won the lottery last month, and he's been putting on airs ever since.

Note. airs 在此用複數, 意旨 "做作; 裝模作樣", put on airs 指擺出一副自以為是了不起或比別人重要, 優秀的樣子. 

2016年2月21日 星期日

[ 英語發燒句 ] Part-16

88. "魚與熊掌不可兼得" 
A. If we get a rental car during our vacation, we'll have to stay at cheaper hotels.
B. Oh, well, you can't have your cake and eat it too.

Note. 類似說法 You can't have it both ways ; You can't have the best of both worlds. 

89. "臨陣退縮" 
A. I though you were going to marry your boyfriend sometimes last year.
B. We talked about it, but we both got cold feet so we called it off.

90. "別吊我胃口" 
A. I've heard some juicy gossip about the net secretary at work.
B. Well, don't keep me in suspense. Tell me what you've heard.

91. "有起床氣" 
A. Wow! Jenny is in a really bad mood. Do you know what's wrong?
B. I have no idea. She must have gotten up on the wrong side of the bed this morning.

92. "見機行事; 看著辦" 
A. Do you have your day in London all planned out?
B. Not at all. I'm just going to play it by ear when I get there.

93. "不要妄自菲薄" 
A. I'm thinking I should just take the small pay increase the company is offering.
B. Don't sell yourself short. You are worth a lot more money than they are paying you.

2016年2月19日 星期五

[Linux 常見問題] Shell - Calculate the free disk space in GB

In some case, you may need to know the size of free disk space. Then you can leverage the function below which leverage command df.

Sample Code
Below sample code will return the size in GB of free disk space.
  1. freespace()  
  2. {  
  3.     df --block-size=1G -P $1 | grep -vE '^Filesystem|tmpfs|cdrom|Available' | awk '{ print $4 }'  
  4. }  
This function freespace take one argument and show the free disk space of the given path.

Usage Example 
The command df can show the below output to indicate the free disk space format:
# df -h /
檔案系統 容量 已用 可用 已用% 掛載點
/dev/mapper/centos-root 50G 9.0G 41G 19% /

If you want to show the disk space in GB with the 'G', leveraging the argument -B, --block-size=SIZE (scale sizes by SIZE before printing them)
# df --block-size=1G /
檔案系統 1G-區段 已用 可用 已用% 掛載點
/dev/mapper/centos-root 50 9 41 19% /

Then you want to filter out the line containing the size of free disk space and get rid of the title, try this:
# echo $LANG
# export LANG=en_US.UTF-8 // Change language setting 
# df --block-size=1G /
Filesystem 1G-blocks Used Available Use% Mounted on
/dev/mapper/centos-root 50 9 41 19% /

# df --block-size=1G / | grep -vE '檔案系統|Filesystem'
/dev/mapper/centos-root 50 9 41 19% /

Finally, we just use command awk to retrieve the target field:
# df --block-size=1G / | grep -vE '檔案系統|Filesystem' | awk '{ print $4 }'

[ 英語發燒句 ] Part-15

82. "詞窮" 
A. Tim's never at a loss for words when it comes to talking politics.
B. Yeah, he sure has some strong opinions.

83. "你這是鴕鳥心態" 
A. In my opinion, the company I work for is doing quite well.
B. Then you're burying your head in the sand. They have laid off hundreds of workers recently.

84. "他很開得起玩笑" 
A. Are you guys teasing Edward again?
B. Yeah, but he can take a joke. He knows that we do it because we like him.
A. Yeah, he's such a good sport.

85. "他只是個酒肉朋友" 
A. I cant't believe David didn't agree to help you this weekend.
B. He's just a fair-weather friend. He only shows up when there is fun to be had.

86. "英雄所見略同" 
A. We could go see the orchestra next Saturday.
B. I guess great minds think alike. I already bought tickets.

87. "本末倒置" 
A. I need to find an apartment that is closer to the company I'm applying to.
B. Don't put the cart before the horse. You don't need to move until you actually get the job.

2016年2月18日 星期四

[Linux 常見問題] Shell - Find folder where contains specific file name

Sometimes, you many want to list the folder(s) where contain specific file name. This time, you can leverage command find with argument '-name'

Sample code
Below sample code will look for all folders under specific path which contains '.jazz?' file (? can be any character):
  1. findBuildDirs()  
  2. {  
  3.     find $1 -maxdepth 2 -mindepth 2 -name '.jazz?' -type d | sed 's!/\.jazz[0-9]$!/!' | xargs -r ls -dt1  
  4. }  

Usage Example
First of all, let's check what we have under folder var using command tree:

And we want to find the folder which contains '.jazz?'. Let's use command find this way:
# find var -name '.jazz?'

However, I only want '.jazz?' to exist under the exact depth=2 from var folder. Then we can do it this way:
# find var -maxdepth 2 -mindepth 2 -name '.jazz?'

Now the output is close to our expectation. Next step is to use command sed to remove out the '.jazz?':
# find var -maxdepth 2 -mindepth 2 -name '.jazz?' | sed 's!/\.jazz[0-9]$!/!'

Finally, you many want to list the folder with order in modification time, try this:
// sort by modification time, newest first
# find var -maxdepth 2 -mindepth 2 -name '.jazz?' | sed 's!/\.jazz[0-9]$!/!' | xargs -r ls -td1

[ 英語發燒句 ] Part-14

73. "別坐失良機" 
A. I still have a few more days to apply for the refund on my income tax.
B. Don't let it slip through your fingers. Go take care of it right now.

Note. 類似說法 Don't let it get away ; Don't miss your chance. 

74. "我瞎猜的" 
A. Do you know who played the part of the villain in this film?
B. I'll say Brad Pitt, but that's just a shot in the dark.

75. "他根本應付不來" 
A. Is Lawrence still working full-time and going to school at night?
B. Yes, but not for long. He's in over his head, and there's no way he can keep doing both.

Note. sb is in over one's head 原指 "水深超過某人頭頂" , 用來比喻 "置身應付不了的情境", 有不自量力的意思. 

76. "你決定" 
A. Should we wait for Ken a little longer or just go into the theater without him?
B. He's your boyfriend, Denise, so it's your call.

Note. 類似說法: It's your choice; It's your decision ; It's up to you 

77. "撐著點" 
A. I am so tired, but I need to finish this project tonight.
B. Just hang in there! It should take you only a few more hours to complete it.

78. "不相上下" 
A. Which cell phone are you going to get?
B. Well, I've been comparing the features of the two that I like, and right now they're neck and neck.

Note. 這個說法來自賽馬, 當馬以頸先持奪點, 稱為 the horse wins by a nect, 當兩匹馬呈現 neck and neck 說明競爭激烈, 勝負難分. 

79. "我對...一無所知" 
A. Can you help me setup this computer program?
B. I won't be much help. I know zip about computers.

Note. zip 做名詞指 拉鍊, 由於音近 zero, 故在美式口語用來表示 "無, 沒有 (nothing at all)" 

80. "種什麼因, 得什麼果" 
A. I can't believe that Tim is so mean to his employees.
B. Well, what goes around comes around. He'll be treated the same way someday.

81. "試了再說" 
A. Is that a peanut butter and banana sandwich you're making? What a weird combination!
B. It tastes really good. Don't knock it till you've tried it.

Note. 類似說法: You'll never know until you try. 

2016年2月17日 星期三

[Linux 文章收集] Shell scripting: Write message to a syslog / log file

Source From Here 
syslog is the protocol as well as application to send message to Linux system logfile located at /var/log directory. Sysklogd provides two system utilities which provide support for system logging and kernel message trapping. Usually most program and apps use C or syslog application / library sending syslog messages. But how do you send message from a shell prompt or shell script? 

logger command 
Use logger command which is a shell command interface to the syslog system log module. It makes or writes one line entries in the system log file from the command line. Log message 'System rebooted for hard disk upgrade': 
# logger System rebooted for hard disk upgrade
# tail -f /var/log/messages
Feb 17 05:11:59 localhost root: System rebooted for hard disk upgrade

You can use logger command from a shell script. Consider following example: 
  1. #!/bin/bash  
  2. HDBS="db1 db2 db3 db4"  
  3. BAK="/sout/email"  
  4. [ ! -d $BAK ] && mkdir -p $BAK || :  
  5. /bin/rm $BAK/*  
  6. NOW=$(date +"%d-%m-%Y")  
  7. ATTCH="/sout/backup.$NOW.tgz"  
  8. [ -f $ATTCH ] && /bin/rm $ATTCH  || :  
  9. MTO="you@yourdomain.com"  
  10. for db in $HDBS  
  11. do  
  12. FILE="$BAK/$db.$NOW-$(date +"%T").gz"  
  13. mysqldump -u admin -p'password' $db | gzip -9 > $FILE  
  14. done  
  15. tar -jcvf $ATTCH $BAK  
  16. mutt -s "DB $NOW" -a $ATTCH $MTO <
  17. DBS $(date)  
  18. EOF  
  19. "$?" != "0" ] &&  logger "$0 - MySQL Backup failed" || :  
Last line will log a message in /var/log/messages file if backup failed. 

Other usage 
To log a message contained in the /var/log/myapp.log file, use: 
// -f, --file : log the contents of this file
# logger -f /var/log/myapp.log

Log the message to standard error (screen), as well as the system log: 
// -s, --stderr: output message to standard error as well
# logger -s "Hard disk full"

Maker your log with tag: 
// -t, --tag : mark every line with this tag
# logger -t 'john' hello mary
# tail /var/log/messages
Feb 17 05:24:02 localhost john: hello mary

Refer to the man page for more options: 
# man logger
# man syslogd

Tsung's Blog - Linux 如何將資料寫到 Syslog 
鳥哥 Linux 基礎文件 - 第十八章、認識與分析登錄檔

[ Python 常見問題 ] How to get symbolic link target in Python?

  Source From  Here Question How do I extract the target path from a  symbolic link ? HowTo The problem with  os .readlink()  is it will onl...