『神器点滴之Emacs』用emacs编写shell script?

都说Emacs是万能的,但从没想到emacs居然可以作为脚本语言来编写linux系统shell script。对于熟悉linux shell编程的同学来说。这也许是开始eLisp世界的一个更好的入口。。。


下面的例子示范了shell script中最常用的几个任务:

1. 读取命令行参数

2. 遍历命令行参数

3. 输出到stdout

4. 输出到stderr

5. 执行外部命令

6. 获取外部命令输出


hello.el

#!/usr/local/bin/emacs --script

;; find your emacs with : "which emacs" and set to the first line

(princ "This is message to stdout\n")

(message "This is err message to stderr")

(setq args command-line-args)

(princ (format "\nread command line with variable : %s\n" args))

(princ "\nenum arguments with car\n")

(setq i 0)

(while (setq arg (car args))

(princ (format "arg[%d] = %s\n" i arg))

(setq args (cdr args))

(setq i (1+ i)))

(princ "\nenum arguments with nth\n")

(setq args command-line-args)

(setq i 0)

(while (setq arg (nth i args))

(princ (format "arg[%d] = %s\n" i arg))

(setq i (1+ i)))

(princ "\nrun shell command with shell-command-to-string\n")

(setq ret (shell-command-to-string "date"))

(princ (format "shell execute result = %s" ret))

(princ "\nstart speed test\n")

(setq num 0)

(setq total 0)

(setq start (current-time))

(while (<= num 10000000)

(setq total (+ total num))

(setq num (+ num 1))

)

(setq end (current-time))

(princ (shell-command-to-string "date"))

(setq cost (- (nth 1 end) (nth 1 start)))

(princ (format "loop for %d times cost %d s\n" num cost))

(princ (format "speed = %d loops/s\n" (/ num cost)))


运行结果:

xxx@ubuntu:~/src/emacs$ ./hello.el 1 2 3 "4 5 6 7 8"

This is message to stdout

This is err message to stderr

read command line with variable : (/usr/local/bin/emacs -scriptload ./hello.el 1 2 3 4 5 6 7 8)

enum arguments with car

arg[0] = /usr/local/bin/emacs

arg[1] = -scriptload

arg[2] = ./hello.el

arg[3] = 1

arg[4] = 2

arg[5] = 3

arg[6] = 4 5 6 7 8

enum arguments with nth

arg[0] = /usr/local/bin/emacs

arg[1] = -scriptload

arg[2] = ./hello.el

arg[3] = 1

arg[4] = 2

arg[5] = 3

arg[6] = 4 5 6 7 8

run shell command with shell-command-to-string

shell execute result = Mon Aug 17 21:09:36 HKT 2015

start speed test

Mon Aug 17 21:09:38 HKT 2015

loop for 10000001 times cost 2 s

speed = 5000000 loops/s

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,792评论 0 33
  • 到巴黎的那个晚上,怡兰又做了那个梦。这次她是在一家小酒吧的门口等火车,天上的云朵跟她说你好,对面的街上还跑出了一只...
    泥巴姑娘的影子阅读 401评论 0 0
  • 今天我们的睡前故事时间读的是刘墉的《没有赢!》其中谈到了海明威和尼采的名言。海明威在《老人与海》里面说:“...
    我是希瑞2017阅读 397评论 0 2
  • 初雨一场 翛翛落了来 雨花漫了遍地 凉了茶水却不凉心意 被虫吃过的黄叶孤零零的 不偏不倚画在窗外的老树上 放眼望去...
    艽艽艽艽阅读 310评论 18 7
  • 恬浅阅读 138评论 0 1